Click here to Skip to main content
6,291,522 members and growing! (14,557 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Advanced

how to create columns dynamically in a grid view

By SaidevKumar

This article describes about how to create columns dynamically in a grid view.
C#, Windows, .NET, ASP.NET, Visual Studio, Dev
Posted:17 Mar 2006
Views:100,497
Bookmarked:31 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
15 votes for this article.
Popularity: 4.64 Rating: 3.95 out of 5
1 vote, 6.7%
1

2

3
4 votes, 26.7%
4
10 votes, 66.7%
5

Sample Image - dynamic_Columns_in_Grid.jpg

Introduction

This article describes about how to create columns dynamically in a grid view.
Many times we have the requirement where we have to create columns dynamically.
This article describes you about the dynamic loading of data using the DataTable as the datasource.

Details of the Grid

Let�s have a look at the code to understand better.

 

Create a gridview in the page,

  1. Drag and drop the GridView on to the page

Or

  1. Manually type GridView definition in the page.

 

<table border="0" cellpadding="0" cellspacing="0">

            <tr>

                <td>

                    <strong>Dynamic Grid</strong></td>

            </tr>

            <tr>

                <td>

                    <asp:GridView ID="GrdDynamic" runat="server" AutoGenerateColumns="False">

                    <Columns>

                    </Columns>

                    </asp:GridView>

                   

                </td>

            </tr>

        </table>

 

With this we are done with creating a GridView in the page. Let�s move on to the code- beside to understand the background history of the page.

 

public partial class _Default : System.Web.UI.Page

{

    #region constants

    const string NAME = "NAME";

    const string ID = "ID";

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

        loadDynamicGrid();

    }

 

    private void loadDynamicGrid()

    {

        #region Code for preparing the DataTable

 

        //Create an instance of DataTable

        DataTable dt = new DataTable();

       

        //Create an ID column for adding to the Datatable

        DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));

        dcol.AutoIncrement = true;

        dt.Columns.Add(dcol);

 

        //Create an ID column for adding to the Datatable

        dcol = new DataColumn(NAME, typeof(System.String));

        dt.Columns.Add(dcol);

 

        //Now add data for dynamic columns

        //As the first column is auto-increment, we do not have to add any thing.

        //Let's add some data to the second column.

        for (int nIndex = 0; nIndex < 10; nIndex++)

        {

            //Create a new row

            DataRow drow = dt.NewRow();

 

            //Initialize the row data.

            drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));

 

            //Add the row to the datatable.

            dt.Rows.Add(drow);

        }

        #endregion

 

        //Iterate through the columns of the datatable to set the data bound field dynamically.

        foreach (DataColumn col in dt.Columns)

        {

            //Declare the bound field and allocate memory for the bound field.

            BoundField bfield = new BoundField();

 

            //Initalize the DataField value.

            bfield.DataField = col.ColumnName;

 

            //Initialize the HeaderText field value.

            bfield.HeaderText = col.ColumnName;

 

            //Add the newly created bound field to the GridView.

            GrdDynamic.Columns.Add(bfield);

        }

 

        //Initialize the DataSource

        GrdDynamic.DataSource = dt;

 

        //Bind the datatable with the GridView.

        GrdDynamic.DataBind();

    }

}

Let�s start dissecting right from the top,

 

After the page declaration, I have created 2 constants which represent the fields in the outputted grid. After that I am calling the loadDynamicGrid() method which will actually work for you. In this method,

  1. Creating a DataTable which will hold the table definition and data for the GridView. This table is used as a DataSource for the GridView
  2. Once the DataTable is created, I am creating 2 columns, ID & Name of type integer (ID) and string (Name) and adding them to the DataTable.
  3. Since the table structure is ready, I am generating some sample data by iterating through a loop for displaying in the GridView.
  4. Now I am iterating through the Columns of the DataTable to create the dynamic columns in the Gridview.
  5. The logic behind creating dynamic column starts by creating a BoundField instance.
  6. Once the BoundField is created, I am initializing the DataField and HeaderText with the column name of the DataTable.
  7. After the BoundField�s basic necessary properties are defined. I am adding the newly created bound field to the GridView control
  8. Once the creation of the dynamic columns is completed, I am assigning the DataSource of the GridView and calling the DataBind method to load the GridView with data dynamically.

 

 

That�s all your dynamic GridView is ready. I hope this information would be helpful.

 

In my next article, I will describe about how to create TemplateColumn dynamically. By now, you must have understand how easy is creating BoundColumn. To create any other type of columns like asp:ButtonField, asp:CheckBoxField, asp:CommandField, asp:HyperLinkField, asp:ImageField the logic & strategy is same, except the template column.

Enjoy programming.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

SaidevKumar


Member

Occupation: Architect
Company: aAmbit Inc
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
Generalhow to get the data that is alrady enterd in grid? Pinmemberkumar Umesh1:38 23 Dec '08  
Generalhow to make the dynamic grid view editable PinmemberMember 423285722:08 20 Oct '08  
GeneralThanks PinmemberNishant Rana (Nishu)3:02 21 Sep '07  
GeneralNeeds Paging and Sorting PinmemberJasonDWilson6:00 4 Apr '07  
Questionhyperlink column Pinmembergilavaa23:46 27 Aug '06  
Questiongridview header Pinmembero5ama19:25 14 Aug '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 17 Mar 2006
Editor:
Copyright 2006 by SaidevKumar
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project