【问题标题】:Cannot Sort GridView after using DataBind()使用 DataBind() 后无法对 GridView 进行排序
【发布时间】:2013-08-11 06:25:06
【问题描述】:

我有一个 GridView,它已经从 SqlDataSource 获取了一些数据。

GridView 允许排序分页选择

现在,当我单击 button 时,我正在创建一个带有新查询的新 DataSource,并将新的 DataSource 分配给此网格,然后我使用 .DataBind() 进行更新这个网格,但在那之后,我无法对任何列进行排序。

动态创建新数据源

SqlDataSource data = new SqlDataSource();
data.ConnectionString = SqlDataSource1.ConnectionString;
data.ProviderName = SqlDataSource1.ProviderName;
data.SelectCommand = "SELECT * FROM USERS";
GridView2.DataSourceID = "";
GridView2.DataSource = data;
GridView2.DataBind();

我尝试使用以下内容:

GridView2.AllowSorting = true;

还是不行,这是我得到的错误。

我在这里错过了什么?

【问题讨论】:

  • 在gridview排序后找不到数据源,所以它会发生。我遇到了这个错误。

标签: c# asp.net sorting gridview data-binding


【解决方案1】:

如果更改 SQLDataSource 的原因是因为您想在单击按钮时执行新查询;您可以在不创建新数据源的情况下执行此操作:

protected void yourButton_Click(object sender, EventArgs e)
{
   // dsYourDataSource is the SQLDataSource that is already connected to your gridview
   dsYourDataSource.SelectCommand = "SELECT * FROM USERS";
   yourGridView.DataBind();
}

这可能会有所帮助。

【讨论】:

  • 是的,这就是我想做的。谢谢。
【解决方案2】:

如果在 GridView 控件上设置 AllowPaging="true" 或 AllowSorting="true" 而不使用 DataSourceControl 数据源(即 SqlDataSource、ObjectDataSource),则会遇到以下错误:

在 GridView 控件上更改页面时:

The GridView 'GridViewID' fired event PageIndexChanging which wasn't handled.

单击列名以对 GridView 控件上的列进行排序时:

The GridView 'GridViewID' fired event Sorting which wasn't handled.

由于未将 GridView 的 DataSourceID 属性设置为 DataSourceControl 数据源,因此您必须添加事件处理程序以进行排序和分页。

this SO 问题中的答案可能会对您有所帮助。

我曾经在我的一个项目中使用过this custom control。您可以从链接下载库并使用自定义 GridViewEx 控件。它运作良好。它看起来和真实的一样:

<cc:GridViewEx ID="gv" runat="server" AllowPaging=True AllowSorting=True 
        OnDataSourceRequested="gv_DataSourceRequested" 
        AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"  />
        ... 
    </Columns>
</cc:GrdiViewEx>

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 2015-06-11
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多