Friday, October 12, 2012

ASP.NET: 'GridView1' fired event Sorting which wasn't handled. Even with LinqDataSource in Use

 Symptom:

  • I have written an ASP.NET application with a GridView (any bound control) and enabled sorting on the control. 
  • I have manually "swapped" the LinqDataSource by another. In my case I have several that contain different Dynamic LINQ statements in them. Next thing you get the following error and the columns will not sort.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:
System.Web.HttpException: The GridView 'GridView1' fired event Sorting which wasn't handled.


Root Cause: 

You are likely to have assigned a LinkDataSource to the DataSource properly. This will not work.

Fix:

If your situation is exactly like mine, like below:

       if (false==String.IsNullOrEmpty(like))
        {
            GridView1.DataSource = this.LinqDataSourceDateDesc;
        }
        else
        {
            GridView1.DataSource = this.LinqDataSource2;
        }
        GridView1.DataBind();


Then this will not work.

Fix this to use the ID of the Data Source, and the event for the sort will hook right back up again.

       if (false==String.IsNullOrEmpty(like))
        {
            GridView1.DataSourceID = "LinqDataSourceDateDesc";
        }
        else
        {
            GridView1.DataSourceID = "LinqDataSource2";
        }
        GridView1.DataBind();


Side Note:

Often when I get stuck with a problem like this, I write a simple test program that would demonstrate the situation. In this day and age, many application projects are already scaffoldded so it's just easy to come up with something quickly. In my case the grid was working initially when I built everything from the designer but as soon as I try to go fancy by assigning the data source, it broke. So this way I went back reproducing basically the original flavor, then looked at the source (in this case in the Default.aspx) and that worked, and quickly realized that it is the DataSourceID they use to bind, no other codes to hookup the events were in this simple code. 

I have seen many novice engineers getting stuck for hours or even days on an issue. If they simply wrote a case to demonstrate the issue then they could have spent much less time fixing the issue.

No comments: