如果使用自定义数据源,如何对 ASP.NET GridView 中的列进行排序? [英] How to sort columns in an ASP.NET GridView if using a custom DataSource?
问题描述
当我使用自定义 SqlDataSource 时,我无法让我的 GridView 使用户能够对一列数据进行排序.
I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.
我有一个 GridView,其中 HTML 中 ASP 引用中的代码最少:
I have a GridView in which the code in the ASP reference to it in the HTML is minimal:
<asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True">
</asp:GridView>
在代码隐藏中,我附加了一个动态创建的 SqlDataSource(它包含的列并不总是相同,因此用于创建它的 SQL 是在运行时构造的).例如:
In the code-behind I attach a dynamically-created SqlDataSource (the columns it contains are not always the same so the SQL used to create it is constructed at runtime). For example:
我设置了列...
BoundField column = new BoundField();
column.DataField = columnName;
column.HeaderText = "Heading";
column.SortExpression = columnName;
grid.Columns.Add(column);
数据源...
SqlDataSource dataSource = new SqlDataSource(
"System.Data.SqlClient",
connectionString,
generatedSelectCommand);
然后是网格视图...
grid.DataSource = dataSource;
grid.DataKeyNames = mylistOfKeys;
grid.DataBind();
目前,当我希望它对列数据进行排序时,当用户单击列标题时,没有任何反应.有人知道我缺少什么吗?
At the moment nothing happens when a user clicks on a column heading when I'd expect it to sort the column data. Anyone any ideas what I'm missing?
如果有更好的方法来做这件事也会有帮助,因为这对我来说看起来很混乱!
If there's a nicer way of doing this that would be helpful too as this looks messy to me!
推荐答案
首先需要添加一个事件:
First you need to add an event:
<asp:GridView AllowSorting="True" OnSorting="gvName_Sorting" ...
然后那个事件看起来像:
Then that event looks like:
protected void gvName_Sorting( object sender, GridViewSortEventArgs e )
{
...
//rebind gridview
}
您基本上必须再次获取数据.
You basically have to get your data again.
你说得对,它看起来很乱,还有更好的方法:ASP.Net MVC
You're right that it looks messy and there is a better way: ASP.Net MVC
不幸的是,这是一个完全不同的页面模型.
Unfortunately that's a drastically different page model.
这篇关于如果使用自定义数据源,如何对 ASP.NET GridView 中的列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!