GridView’GridView1’触发事件排序未处理
作者:互联网
我已经在C#中使用工具箱创建了一个gridview,
它可以显示&对我的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();
以下是我的gridview&我的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();
标签:gridview,data-binding,sqldatasource,c 来源: https://codeday.me/bug/20191201/2082467.html