Click here to Skip to main content
Licence 
First Posted 17 Mar 2006
Views 268,166
Bookmarked 57 times

how to create columns dynamically in a grid view

By | 17 Mar 2006 | Article
This article describes about how to create columns dynamically in a grid view.

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

Devakumar Sai Chinthala

Founder
Articledean.com & conveygreetings.com
United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionKinda worthless PinmemberMember 99049010:43 23 May '12  
GeneralMy vote of 5 Pinmembersravani.v20:11 20 May '12  
QuestionI understand how to dynamically add but how do you preserve values of control inside gridview PinmemberJephunneh Malazarte23:42 14 Feb '12  
GeneralMy vote of 1 Pinmembernavjyotjss22:52 10 Nov '11  
GeneralWorked a treat with an AccordionPane exercise PinmemberIPI Paul3:34 12 May '11  
GeneralMy vote of 4 Pinmemberhasan.rounak22:06 13 Feb '11  
GeneralMy vote of 4 Pinmemberkiranpatel1:26 17 Jan '11  
QuestionDynamic create a Gridview. PinmemberMember 303777123:53 24 Aug '09  
Generalclick event for the Imagebutton Pinmembervijay r11:50 22 Jul '09  
Questionhow to get the data that is alrady enterd in grid? Pinmemberkumar Umesh0:38 23 Dec '08  
Questionhow to make the dynamic grid view editable PinmemberMember 423285721:08 20 Oct '08  
GeneralThanks PinmemberNishant Rana (Nishu)2:02 21 Sep '07  
Thanks for posting and sharing your work.
 
Nishant Rana

GeneralNeeds Paging and Sorting PinmemberJasonDWilson5:00 4 Apr '07  
Questionhyperlink column Pinmembergilavaa22:46 27 Aug '06  
Questiongridview header Pinmembero5ama18:25 14 Aug '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 17 Mar 2006
Article Copyright 2006 by Devakumar Sai Chinthala
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid