>

Programmatically Created GridView not Sorting

Posted on December 14, 2011 By

There have been times when I needed to programmatically create a DataGrid in the code behind.  Perhaps this was a server control, WebPart, or just a regular page.  In some case, I have found that sorting will not work on the GridView when it is programmatically created.  This is usually caused by when the controls are created late in the life cycle process.  In most cases, the fix has been to add EnsureChildControls to the OnInit method of the control.

To make sure that your programmatically created GridView sorts properly you should follow these 5 steps.  (Here I will assume that you are binding to a SalDataSource).

1. Override the CreateChildControls method and create (instantiate) the GridView and the SqlDataSource in this method.

2. Add both controls to the Page’s Control collection.

3. Be sure to set the AllowSorting property to true on the GridView.

4. Set the GridView’s DataSourceID to the ID of the SQLDataSouce (be sure the controls have already been added to the page).

5. Override the pages OnInit method and call EnsureChildControls from here.

 If EnsureChildControl is not called during the init phase it is possible that the GridView will be created too late for effective sorting.  If it is created too late it may rebind with the DataSource and override the sorting.

The code below demonstrates with process:

protected GridView TheGridView;
protected SqlDataSource TheDataSource;

protected override void CreateChildControls()
{
//Create and setup the GridView
TheGridView = new GridView();
TheGridView.ID = "TheGridView";
TheGridView.AutoGenerateColumns = true;
TheGridView.AllowSorting = true;

//Create and setup the SqlDataSource
TheDataSource = new SqlDataSource();
TheDataSource.ID = "TheDataSource";
TheDataSource.Init+=new EventHandler(TheDataSource_Init);

Controls.Add(TheGridView);
Controls.Add(TheDataSource);
TheGridView.DataSourceID = TheDataSource.ID;

base.CreateChildControls();
}

protected override void OnInit(EventArgs e)
{
EnsureChildControls();
base.OnInit(e);
}

void TheDataSource_Init(object sender, EventArgs e)
{
//setup the SqlDataSource here - connect strings, select command, etc.

}

ASP.Net     , , , , ,