Pedro Henrique Rissato Pedro Henrique Rissato - 13 days ago 8
ASP.NET (C#) Question

Sorting GridView on code behind. Gridview generated dynamically. OnSorting method not been called

I need to create a lot of

GridView
s to show on an aspx page.

Then, I've created a method to generate these
GridView
s, based on an array of names and
DataTable
s.

Anyway, each
GridView
is generated as follows:

GenerateGridView(string gvName, DataTable dtGridView){
GridView Gview = new GridView();
Gview.ID = gvName;
Gview.AutoGenerateColumns = true;
Gview.CssClass = "table table-responsive table-condensed table-striped table-bordered";
Gview.CellPadding = 4;
Gview.GridLines = 0;
Gview.AllowPaging = false;
Gview.Attributes.Add("Font-Size", "Smaller");
Gview.Attributes.Add("HeaderStyle-Font-Size", "Small");
Gview.AllowSorting = true;
}


Problem: I need the
OnSorting
method. But I don't have all of the
GridView
s names, they will be generated dynamically (The Gvied.ID or gridview ID is generated dynamically based on table names from a SELECT command).

So I can't create a
protected void gridViewName_OnSorting
method.

The
Gridview
is generated smooth. But every time I click on a header, I get an


System.Web.HttpException


sorting exception.

I created a generic Sorting:

protected void gvSorting(object sender, GridViewSortEventArgs e)


Then I added an attribute to all
GridView
s in
GenerateGridview(..)
:

Gview.Attributes.Add("OnSorting", "gvSorting");


But, I keep getting the Http Sorting Exception. I debugged the code, and, besides


OnSorting = gvSorting


appears on the generated
GridView
s, that error persists.

Answer

All you have to do is add the Sorting method to the GridView in GenerateGridView

Gview.Sorting += GridViewAll_Sorting;

And create a sorting method for all the GridViews

protected void GridViewAll_Sorting(object sender, GridViewSortEventArgs e)
{
    //cast the sender as a gridview
    GridView Gview = sender as GridView;

    //get the datatable from viewstate (or another source)
    DataTable dt = ViewState["dtGridView"] as DataTable;

    //sort the datatable
    dtGridView.DefaultView.Sort = e.SortExpression;

    //bind the data to the gridview
    Gview.DataSource = dtGridView;
    Gview.DataBind();
}