如何在使用自定义数据源在ASP.NET GridView的列进行排序? [英] How to sort columns in an ASP.NET GridView if using a custom DataSource?
问题描述
我不能让我的GridView控件,让用户排序数据的列时,我使用自定义SqlDataSource的。
I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.
我有一个GridView,其中在ASP参考它在HTML中code是最小的:
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>
在code-后面附上一个动态创建的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);
然后在GridView ...
then the gridview...
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屋!