0

我在 GridView 中添加了一个排序选项,但不知道为什么它不起作用。

这是我的标记:

<asp:GridView ID="GridView1"  AllowSorting="true" runat="server" Width="100%"
    AutoGenerateColumns="False" DefaultSortDirection="Ascending" DataKeyNames="ClientAccountNumber,Invoice" AllowPaging="true"OnSorting="GridView1_Sorting">
 <Columns>
<asp:TemplateField HeaderText="Invoice" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" SortExpression="[Invoice]">
       <ItemTemplate>
      <asp:Label ID="lblInvoice" runat="server" Text='<%# Eval("Invoice")%>'></asp:Label>
              </ItemTemplate>
        </asp:TemplateField>    
</Columns>

代码:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
   // bindGrid();

    DataTable dataTable = GridView1.DataSource as DataTable;
    if (dataTable != null)
    {
        DataView dataView = new DataView(dataTable);
        dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
        GridView1.DataSource = dataView;
        GridView1.DataBind();
    }
}

绑定gridview的代码

private void bindGrid()
{
    try
    {
        if (int.Parse(lblAccountNo.Text.ToString()) > 0)
        {
            _clientTransection.AccountNo  =Convert.ToInt32(lblAccountNo.Text.ToString());
           Collection<ClientTransInvoiceRows> _clientList =    _clientTransection.Execute();
           GridView1.DataSource = _clientList;
           GridView1.DataBind();
        }
    }
    catch
    {
    }
}

这一行:

DataTable dataTable = GridView1.DataSource as DataTable;

给我null。是否有其他选项可以对我的 GridView 进行排序?

4

1 回答 1

1

不幸的是,这不会以这种方式工作。DataSource属性仅在数据绑定期间不为空。在页面生命周期的所有其他阶段(即在事件处理期间)它为空,除非您明确初始化它。

但是,在您的情况下,解决方案很简单-只需按照您之前绑定的方式重新绑定网格,只需考虑排序信息即可。首先修改bindGrid方法以考虑排序。

private void bindGrid(string sort)
{
    try
    {
        if (int.Parse(lblAccountNo.Text.ToString()) > 0)
            _clientTransection.AccountNo = Convert.ToInt32(lblAccountNo.Text.ToString());
        Collection<ClientTransInvoiceRows> _clientList = _clientTransection.Execute();

        if (string.IsNullOrEmpty(sort))
        {
            // apply sorting
        }

        GridView1.DataSource = _clientList;
        GridView1.DataBind();
    }

    catch
    {
    }
}

然后用适当的参数调用它:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    string sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    bindGrid(sort);
}
于 2013-06-26T09:00:07.910 回答