Click here to Skip to main content
15,867,704 members
Articles / Web Development / ASP.NET
Article

how to create columns dynamically in a grid view

Rate me:
Please Sign up or sign in to vote.
4.53/5 (47 votes)
17 Mar 20064 min read 553.5K   4.8K   66   21
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.

 <o:p>

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.

 <o:p>

<table border="0" cellpadding="0" cellspacing="0"><o:p>

            <tr><o:p>

                <td><o:p>

                    <strong>Dynamic Grid</strong></td><o:p>

            </tr><o:p>

            <tr><o:p>

                <td><o:p>

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

                    <Columns><o:p>

                    </Columns><o:p>

                    </asp:GridView><o:p>

                    <o:p>

                </td><o:p>

            </tr><o:p>

        </table>

 <o:p>

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.

 <o:p>

public partial class _Default : System.Web.UI.Page<o:p>

{<o:p>

    #region constants<o:p>

    const string NAME = "NAME";<o:p>

    const string ID = "ID";<o:p>

    #endregion<o:p>

 <o:p>

    protected void Page_Load(object sender, EventArgs e)<o:p>

    {<o:p>

        loadDynamicGrid();<o:p>

    }<o:p>

 <o:p>

    private void loadDynamicGrid()<o:p>

    {<o:p>

        #region Code for preparing the DataTable<o:p>

 <o:p>

        //Create an instance of DataTable<o:p>

        DataTable dt = new DataTable();<o:p>

        <o:p>

        //Create an ID column for adding to the Datatable<o:p>

        DataColumn dcol = new DataColumn(ID ,typeof(System.Int32));<o:p>

        dcol.AutoIncrement = true;<o:p>

        dt.Columns.Add(dcol);<o:p>

 <o:p>

        //Create an ID column for adding to the Datatable<o:p>

        dcol = new DataColumn(NAME, typeof(System.String));<o:p>

        dt.Columns.Add(dcol);<o:p>

 <o:p>

        //Now add data for dynamic columns<o:p>

        //As the first column is auto-increment, we do not have to add any thing.<o:p>

        //Let's add some data to the second column.<o:p>

        for (int nIndex = 0; nIndex < 10; nIndex++)<o:p>

        {<o:p>

            //Create a new row<o:p>

            DataRow drow = dt.NewRow();<o:p>

 <o:p>

            //Initialize the row data.<o:p>

            drow[NAME] = "Row-" + Convert.ToString((nIndex + 1));<o:p>

 <o:p>

            //Add the row to the datatable.<o:p>

            dt.Rows.Add(drow);<o:p>

        }<o:p>

        #endregion<o:p>

 <o:p>

        //Iterate through the columns of the datatable to set the data bound field dynamically.<o:p>

        foreach (DataColumn col in dt.Columns)<o:p>

        {<o:p>

            //Declare the bound field and allocate memory for the bound field.<o:p>

            BoundField bfield = new BoundField();<o:p>

 <o:p>

            //Initalize the DataField value.<o:p>

            bfield.DataField = col.ColumnName;<o:p>

 <o:p>

            //Initialize the HeaderText field value.<o:p>

            bfield.HeaderText = col.ColumnName;<o:p>

 <o:p>

            //Add the newly created bound field to the GridView.<o:p>

            GrdDynamic.Columns.Add(bfield);<o:p>

        }<o:p>

 <o:p>

        //Initialize the DataSource<o:p>

        GrdDynamic.DataSource = dt;<o:p>

 <o:p>

        //Bind the datatable with the GridView.<o:p>

        GrdDynamic.DataBind();<o:p>

    }<o:p>

}

Let’s start dissecting right from the top,

 <o:p>

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.

 <o:p>

 <o:p>

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

 <o:p>

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


Written By
Founder Articledean.com & conveygreetings.com
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mittu Machhi27-Feb-13 19:16
Mittu Machhi27-Feb-13 19:16 
GeneralMy vote of 5 Pin
AshishChaudha26-Feb-13 17:28
AshishChaudha26-Feb-13 17:28 
GeneralMy vote of 5 Pin
Mitesh Machhi5-Feb-13 20:10
Mitesh Machhi5-Feb-13 20:10 
MY 5 THIS. NICE ARTICLE AND EASY TO UNDERSTAND.
GOOD WORK.
QuestionAdding a text box for capturing answers Pin
klca28-Dec-12 6:18
klca28-Dec-12 6:18 
QuestionKinda worthless Pin
Member 99049023-May-12 10:43
Member 99049023-May-12 10:43 
GeneralMy vote of 5 Pin
sravani.v20-May-12 20:11
sravani.v20-May-12 20:11 
QuestionI understand how to dynamically add but how do you preserve values of control inside gridview Pin
Jephunneh Malazarte14-Feb-12 23:42
Jephunneh Malazarte14-Feb-12 23:42 
GeneralMy vote of 1 Pin
navjyotjss10-Nov-11 22:52
navjyotjss10-Nov-11 22:52 
GeneralWorked a treat with an AccordionPane exercise Pin
IPI Paul12-May-11 3:34
IPI Paul12-May-11 3:34 
GeneralMy vote of 4 Pin
Rounak Hasan13-Feb-11 22:06
Rounak Hasan13-Feb-11 22:06 
GeneralMy vote of 4 Pin
kiranpatel17-Jan-11 1:26
kiranpatel17-Jan-11 1:26 
QuestionDynamic create a Gridview. Pin
Member 303777124-Aug-09 23:53
Member 303777124-Aug-09 23:53 
Generalclick event for the Imagebutton Pin
vijay r22-Jul-09 11:50
vijay r22-Jul-09 11:50 
Questionhow to get the data that is alrady enterd in grid? Pin
kumar Umesh23-Dec-08 0:38
kumar Umesh23-Dec-08 0:38 
Questionhow to make the dynamic grid view editable Pin
Member 423285720-Oct-08 21:08
Member 423285720-Oct-08 21:08 
AnswerRe: how to make the dynamic grid view editable Pin
Shail Mishra21-Feb-14 23:53
Shail Mishra21-Feb-14 23:53 
GeneralThanks Pin
Nishant Rana (Nishu)21-Sep-07 2:02
Nishant Rana (Nishu)21-Sep-07 2:02 
GeneralNeeds Paging and Sorting Pin
JasonDWilson4-Apr-07 5:00
JasonDWilson4-Apr-07 5:00 
Questionhyperlink column Pin
gilavaa27-Aug-06 22:46
gilavaa27-Aug-06 22:46 
Questiongridview header Pin
o5ama14-Aug-06 18:25
o5ama14-Aug-06 18:25 
GeneralAdding Update or Insert Feature Pin
amitsol5-Aug-06 23:31
amitsol5-Aug-06 23:31 

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

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