65.9K
CodeProject is changing. Read more.
Home

how to create columns dynamically in a grid view

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.53/5 (43 votes)

Mar 17, 2006

4 min read

viewsIcon

556601

downloadIcon

4781

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.