How to create GridView programmatically in code behind

Download Sample Project

I have talked about using and customizing GridView, DataGrid and other grid like controls in lot of my previous posts. In this post I am going to discuss how you can build GridView programmatically. First question that you may be asking what do I really need to design and build GridView in code behind and not using designer and control tags. For most cases you may not have to do it. But think for a moment a case where you do not know the number of columns you will need ahead of time and depend on some run time conditions or configuration changes. Then you won't be able to specify column tags in your design view.

I will split this post into multiple parts to tackle different parts of the solution. In this particular post I am going to concentrate mainly on creating the GridView and displaying the data.

  • How to programatically add columns to GridView
  • How to format data into GridView columns at run time

I am not going to discuss how to handle changing data in grid view columns in this post. I will do that in subsequent posts. Here are steps that you will follow to build your GridView at run time.

  • Add a GridView on your ASP.Net page. Your smark up will look like something as shown below.

    <asp:GridView ID="Sales_Grid" runat="server" 
     AutoGenerateColumns="false" GridLines="None" CssClass="salesgrid"

    The most important part of this mark up is that you need to set AutoGenerateColumn property to false. By doing so you will disable GridView from automatically generating any columns.

  • At run time, add columns to GridView. For example following cone snippet shows how BoundField columns are being added to Grid based on a collection that we get at run time.

    void SetupGridStructure()
       var gridColumn = new BoundField();
       foreach (SalesPeriod period in _salePeriods)
          gridColumn = new BoundField();
          gridColumn.HeaderText = period.PeriodName;
  • Subscrive to RowCreated and/or RowDataBouns event(s) on GridView depending on at what stage you want to set the data in the columns. You can see those event specified in first step in the GridView mark up. in these events you will set the data for each columns. The following code snippet shows how I did it for showing some dummy sales figures for each month of the year

    protected void OnGridRowDataBound(object sender, GridViewRowEventArgs e)
          case DataControlRowType.Header:
          case DataControlRowType.DataRow:
    void RenderDataRow(GridViewRowEventArgs args)
        // Accesss the data.
        var rowData = args.Row.DataItem as SalesData;
        // Get product name.
        ..... Rest of the code .....

Attached sample project shows all this in action. There are more features implemented in the sample that I will be discussing in subsequesnt posts.

comments powered by Disqus

Blog Tags