【发布时间】:2014-01-19 17:52:48
【问题描述】:
我有一堂课:
public class CustomInvoice
{
public string InvoiceId { get; set; }
public string Date { get; set; }
public string RecpDate { get; set; }
public string Category { get; set; }
public string TotalValue { get; set; }
public string InvoiceRef { get; set; }
public string Client { get; set; }
public string Status { get; set; }
}
我用数据填充这个类,然后将它绑定到我的 gridview:
List<CustomInvoice> invoices = GetInvoices(url);
InvoiceGrid.DataSource = invoices;
InvoiceGrid.DataBind();
这会正确显示所有信息,但现在我希望能够对其进行排序,所以我使用以下方法添加了一个按钮:
protected void Button1_Click(object sender, EventArgs e)
{
string expression = "InvoiceId";
SortDirection direction = SortDirection.Ascending;
InvoiceGrid.Sort(expression,direction);
}
我还更改了它的 html 以允许排序:
<asp:GridView ID="InvoiceGrid" runat="server" AllowSorting="True" OnSorting="gridView_Sorting"></asp:GridView>
但是,当它运行时,我得到以下异常
System.Web.HttpException (0x80004005): The GridView 'InvoiceGrid' fired event Sorting which wasn't handled.\r\n
有人可以告诉我如何使用按钮的 onclick 对我的 gridview 进行排序吗?
谢谢:)
编辑:
我已尝试将此添加到列标题(忽略按钮)
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = InvoiceGrid.DataSource as DataTable;
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + e.SortDirection;
InvoiceGrid.DataSource = dataView;
InvoiceGrid.DataBind();
}
但是这里的问题是 DataTable 为空,即使我可以看到 invoiceGrid 有数据。
【问题讨论】:
-
你需要实现GridView.Sorting事件
-
你能举个例子吗?
-
@codingstill 我已经进行了编辑,你能发现错误吗?
-
InvoiceGrid.DataSource在回发时应该为空。 1.您可以通过GetInvoices再次获取数据或2.您可以将invoices保存在Session中并重新绑定从会话中获取。 -
我提供给你,使用 Linq。它很灵活,让您可以对数据做任何事情。 codeproject.com/Articles/19154/Understanding-LINQ-C
标签: c# asp.net sorting gridview