Monday, 13 August 2007

Programmatically Adding Columns to GridView

There are cases where you might want to use the same GridView to display diferent columns in a page. This is possible by programmatically adding the columns using the BoundField Object. The key thing to note here is the diference in adding a column to a DataGrid and a GridView, to add a bound column in the DataGrid you should use the BoundColumn object and to add a column to the GridView, you should use a BoundField object. You can create the gridview in your .aspx page and set the sorting and things like that or you can create the complete gridview in your code behind using the GridView class.
The code below shows how to add columns to a gridview that was created in the .aspx page..

--.aspx page--

AllowPaging="True" AllowSorting="True" PageSize="21" EmptyDataText="No data available."
CssClass="gridstyle" GridLines="None" OnSorting="GridViewID_Sorting" OnPageIndexChanging="GridViewID_Paging"
Width="100%">





--.cs page--

private void DefineGridViewColumns()
{
BoundField column = new BoundField(); //You can use the TemplateField object to add a template column
column.HeaderText = "XX";
column.DataField = "ID";
column.SortExpression = "ID";
column.HeaderStyle.CssClass = "titletext";
column.ItemStyle.Width = Unit.Percentage(7);
GridViewID.Columns.Add(column);

column = new BoundField();
column.HeaderText = "RANK";
column.DataField = "RANKNO";
column.SortExpression = "RANKNO";
column.HeaderStyle.CssClass = "titletext";
column.ItemStyle.Width = Unit.Percentage(7);
GridViewID.Columns.Add(column);

if (TimeSpan.Equals("TW"))
{
column = new BoundField();
column.HeaderText = "THIS WEEK";
column.DataField = "XX_TARGET";
column.SortExpression = "XX_TARGET";
column.HeaderStyle.CssClass = "titletext";
column.ItemStyle.Width = Unit.Percentage(10);
GridViewID.Columns.Add(column);
}
}

4 comments:

RAVI KUMAR said...

Hi Junkie,

Thank you for giving this article.It is very important to me.



Thank you,
Ravi

RollerCoaster said...

thanks, just what i needed

Anonymous said...

To generate columns for Data GridView, we can use either automatic column generation based on the data source or C# code to add columns

lee woo said...

Keep your face always toward the sunshine - and shadows will fall behind you. See the link below for more info.

#behind
www.ufgop.org