• How to add columns to GridView dynamically in ASP.NET

    Posted on August 23, 2012 by in ASP.NET, C#, Dotnet

    In this article, I am going to create an example to add columns to GridView dynamically at runtime.

    For more trips and tricks on using GridView, refer to this article:
    GridView tips and tricks using ASP.NET PART 1

    Database Connection
    I am going to use Adventure Works as datasource. Open web.config and add following entry to connection strings element

    <add name="Sql" connectionString="Data Source=(local);Initial Catalog= AdventureWorks;User=testuser;Password=testuser;"    providerName="System.Data.SqlClient"/>

    DataSource:
    The SqlDataSource data source control is simply a control that represents data in an SQL relational database to data-bound controls. The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. The SelectCommand property specifies the SQL statement to execute to retrieve the data.

    <asp:SqlDataSource ID="sqlDSProducts" runat="server" 
    ConnectionString="<%$ ConnectionStrings:Sql %>"
    SelectCommand="SELECT top 10 P.ProductID, P.Name, P.ProductNumber, P.ListPrice, PS.Name AS SubCategoryName FROM Production.Product P
    INNER JOIN Production.ProductSubcategory PS ON P.ProductSubcategoryID = PS.ProductSubcategoryID">
    

    GridView Design:

    <asp:GridView ID="gvProducts"           
        AutoGenerateColumns="False"  CssClass="mGrid"     
        runat="server" >      
        <Columns>        
        </Columns>  
    </asp:GridView>
    

    Source Code:
    In the Page_load event handler of the page, if this is the first time page is loading, we call CreateDynamicGrid function that would add columns to the gridview and binds it with products data.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            CreateDynamicGrid();
        }
    }
    

    In CreateDynamicGrid function, we call the Select function of the SQLDataSource control to fetch products data from database. We iterate through the columns of the resultset and add them to the gridview as bound columns. Finally, we bind the gridview with the resultset.

    private void CreateDynamicGrid()
    {
        //execute the select statement 
        DataView dvProducts = (DataView)sqlDSProducts.Select(DataSourceSelectArguments.Empty);
        DataTable dtProducts = dvProducts.Table;
    
        BoundField boundField = null;
        //iterate through the columns of the datatable and add them to the gridview
        foreach (DataColumn col in dtProducts.Columns)
        {
            //initialize the bound field
            boundField = new BoundField();
    
            //set the DataField.
            boundField.DataField = col.ColumnName;
    
            //set the HeaderText
            boundField.HeaderText = col.ColumnName;
    
            //Add the field to the GridView columns.
            gvProducts.Columns.Add(boundField);
    
        }
        //bind the gridview the DataSource
        gvProducts.DataSource = dtProducts;          
        gvProducts.DataBind();
    }
    

    Output:add columns to gridview dynamically 1

    Be Sociable, Share!
      Post Tagged with , ,

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]

    2 Responsesso far.

    1. Dear Venu Gopal

      Thanks for posting such type of post and share your exp.

      Please keep it up

      Thanks

    2. Chandu says:

      Sir, I want to add another colimn such as Action to perform Edit,Delete options to this Dynamic GridView. How can i add this column at last position to this gridview?

    Leave a Reply