2

I have a GridView that already fetches some data from a SqlDataSource.

The GridView has sorting, paging, selection allowed.

Now when I'm clicking a button, I'm creating a new DataSource with a new Query, and I'm assigning the new DataSource to this Grid, then I use .DataBind() to update this grid, but after that, I cannot sort any column.

Dynamically Creating the new DataSource

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

I tried to use the following:

GridView2.AllowSorting = true;

Still it didn't work, this is the error I get.

enter image description here

What am I missing here?

Ali Bassam
  • 9,691
  • 23
  • 67
  • 117

2 Answers2

2

If the reason for changing the SQLDataSource is because you want to execute a new query on the click of a button; you can do this without creating a new data source:

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();
}

This might help.

Oscar M
  • 61
  • 4
0

If you set AllowPaging="true" or AllowSorting="true" on a GridView control without using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will run into the following errors:

When changing the page on the GridView control:

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

When clicking a column name to sort the column on the GridView control:

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

As a result of not setting the DataSourceID property of the GridView to a DataSourceControl DataSource, you have to add event handlers for sorting and paging.

The answer in this SO question may help you.

Also I have once used this custom control in one my projects. You can download the libarary from the link and use custom GridViewEx control. It works well. It will look same as real one:

<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>
Community
  • 1
  • 1
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98