网格视图';GridView1';激发事件排序,而不是';t已处理
本文关键字:处理 事件 GridView1 视图 网格 排序 | 更新日期: 2023-09-27 18:26:31
我使用c#中的工具箱创建了一个网格视图,它能够显示&对sqldatasource中的项进行排序,但当我更改sqldatasource时,如下面的代码所示,它显示错误"GridView'GridView1'激发的事件排序未处理"
SqlDataSource searchResults = new SqlDataSource(WebConfigurationManager.ConnectionStrings["MyDbConn"].ToString(), "SELECT * FROM Books WHERE id=1");
GridView1.DataSourceID = null;
GridView1.DataSource = searchResults;
GridView1.DataBind();
下面是我的网格视图&我的Default.aspx中的sqldataconnection代码(通过从工具箱拖放创建)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
GridLines="Vertical" Width="748px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" />
<asp:BoundField DataField="BookName" HeaderText="BookName"
SortExpression="BookName" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="ReturnDate" HeaderText="ReturnDate"
SortExpression="ReturnDate" />
<asp:CheckBoxField DataField="Reserve" HeaderText="Reserve"
SortExpression="Reserve" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyDbConn %>"
SelectCommand="SELECT * FROM [Books]"></asp:SqlDataSource>
更新
您不必动态添加新的数据源,因为您只想更改数据源的SelectCommand。只做
SqlDataSource1.SelectCommand = "SELECT * FROM Books WHERE id=1";
gv.DataBind();
如果你想通过搜索词搜索书籍,你可以做一些类似的事情
SqlDataSource1.SelectCommand = "SELECT * FROM Books WHERE id LIKE '%" + searchTxt.Text + "'%";
gv.DataBind();
根据我的经验,动态添加新的数据源似乎会导致严重的问题。
请尝试
SqlDataSource searchResults = new SqlDataSource(WebConfigurationManager.ConnectionStrings["MyDbConn"].ToString(), "SELECT * FROM Books WHERE id=1");
searchResults.ID = "searchResults"; //or something else
this.Controls.Add(searchResults);
GridView1.DataSourceID = searchResults.ID;
GridView1.DataBind();
或更简单的
SqlDataSource searchResults = new SqlDataSource(WebConfigurationManager.ConnectionStrings["MyDbConn"].ToString(), "SELECT * FROM Books WHERE id=1");
this.Controls.Add(searchResults);
GridView1.DataSource = searchResults;
GridView1.DataBind();