Home   |  Articles   |  Resources   |  Humor   |  Feedback       

  Login   Register 

Ads Via DevMavens


Dynamically create a datagrid in ASP.net using C#

Posted by on Sunday, August 15, 2004

Create a dynamic ASP.Net datagrid control and columns using c# code. This example demonstrates how to generate a datagrid control and datagrid columns on the fly in the code behind file based on the results of a SQL Query

For the most part we create a datagrid at design time by just adding a Datagrid control to a web form. One of the disadvantages of this as a developer is that for each report a user requests, a new Web Form needs to be created. Before long your project has hundreds of pages, which becomes in due course a maintenance nightmare.

In this article, we are going to create a simple web form, and create a datagrid dynamically using code. We are then going to add columns to this datagrid based on the results returned via a SQL stored procedure. This dynamically created datagrid will render the results of any SQL Query or stored procedure.

 Let’s start with our simple web page:

  <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
      <asp:PlaceHolder id="PlaceHolder" runat="server" />
    </form>
  </body>


I have added a Placeholder control here, inside of which my Data Grid is going to reside. Now let’s create a stored procedure using the AdventureWorks2000 database called  Dynamic_DataGrid which contains a simple Select statement

SELECT distinct P.ProductID AS Product_ID,
       PSC.Name AS Product_Sub_Category, PC.Name AS Product_Category,
P.StandardCost AS Standard_Cost, P.ListPrice AS List_Price,
PV.AverageLeadTime AS Average_List_Time, PV.MinOrderQty AS Minimum_Quantity,
PV.MaxOrderQty AS Maximum_Quantity, PV.LastReceiptDate AS Last_Reciept_Date
FROM   Product P
INNER JOIN ProductSubCategory PSC ON
P.ProductSubCategoryID = PSC.ProductSubCategoryID
INNER JOIN ProductCategory PC ON
PSC.ProductCategoryID = PC.ProductCategoryID
INNER JOIN ProductVendor PV ON P.ProductID = PV.ProductID


Create a datagrid programatically

Let's see what our code behind file to create a datagrid looks like.

// Instantiate the data grid control
    System.Web.UI.WebControls.DataGrid DataGrid1 =
new System.Web.UI.WebControls.DataGrid();
// the GetDataSet method executes the Stored procedure and populates a dataset ds
   ds = GetDataSet("DynamicDataGridSP1");
// the dataset is used as the data source for our newly created datatrid DataGrid1
   DataGrid1.DataSource=ds;
   DataGrid1.DataBind();
// DataGrid1 is added to the PlaceHolder
   PlaceHolder.Controls.Add(DataGrid1);


   So let’s build and compile this, and see what we get.

The results are not bad: we did what we set out to do. We created the datagrid on the fly, in the code behind file, and populated it with the results of our stored procedure Dynamic_Datagrid. The problem is that our datagrid looks mediocre and our users are not very happy with it. Fortunately, you can set Datagrid properties programmatically.

Setting Datagrid properties in code

      DataGrid1.Width = 600;
      DataGrid1.Height= 400;
      DataGrid1.GridLines = GridLines.Both;
      DataGrid1.CellPadding =1;
      DataGrid1.ForeColor=System.Drawing.Color.Black;
      DataGrid1.BackColor = System.Drawing.Color.Beige;
      DataGrid1.AlternatingItemStyle.BackColor = System.Drawing.Color.Gainsboro;
      DataGrid1.HeaderStyle.BackColor = System.Drawing.Color.Brown;

Now we have a better looking grid, - this example is just a representative sample of a few DataGrid properties. Refer the DataGrid class  to get a comprehensive list of the properties of the DataGrid.

Add Columns to a datagrid dynamically in the code behind

So far we have been making use of the AutoGenerateColumns property of the Datagrid control. When this property is set to true the Grid creates a bound column for each field in data source of the Datagrid. Whereas we haven’t specifically set the property to true, this is the default behavior of the Datagrid. Our columns are not formatted however, and we might get a little more functionality from this code, if we don’t rely on AutoGenerateColumns.

        DataGrid1.AutoGenerateColumns=false;

 After adding the above line of code, we will need to add columns individually to the datagrid. Since I am building on the first example in this article, we will assume I already have a populated DataSet (ds), and I only have one table, so the data is returned in Table[0]. We are going to loop through the columns on the DataTable and add them to our DataGrid. To set the properties of each column we will write a new method: the CreateBoundColumn method.

      foreach(DataColumn c in ds.Tables[0].Columns)
      {
        DataGrid1.Columns.Add(CreateBoundColumn(c));
      }

 

Now, it is time to take a look at the CreateBoundColumn method.

      BoundColumn column = new BoundColumn();
      column.DataField = c.ColumnName;
      column.HeaderText = c.ColumnName.Replace("_"," ");
      column.DataFormatString =setFormating(c);
      return column;

This method creates a new BoundColumn object and binds the column to the associated field in the DataSet. Next the method prettifies the column heading by stripping the '_',  and then sets the formatting of the column based on the data type in the setFormatting method.

Setting Datagrid column formatting in code

Its time to take a look at the setFormatting method.

    private string setFormating(DataColumn bc) 
    {
      string dataType = null;
      switch(bc.DataType.ToString())      
      {     
        case "System.Int32":  
          dataType = "{0:#,###}";
         break;                
        case "System.Decimal":           
          dataType =  "{0:c}";
          break;
        case "System.DateTime":
         dataType="{0:dd-mm-yyyy}";
         break;
        case "System.String":
          dataType="";
          break;
        default:   
          dataType = "";
          break;     
      }
      return dataType;
    }

Of course I haven’t covered all data types, but you can expand the switch statement to cover other data types you might be using.

Note: the data types being used here are NOT the SQL data types, but the .NET data types.

Let’s take a look at our page now.

 Conclusion : There are a lot more properties you could set to make this data grid fit your application needs. In a real world scenario, we would want to add sorting and paging to this too. The intent of this article is, to provide an insight into how to create a web form with a dynamic datagrid, created based on the data returned. Hopefully this will help building applications faster.

 

by Poonam Lall


Comments:

Dynamic Datagrid ....
By webminer on 8/18/2004
Poonam,

Any chance you could post the complete working source rather than just the 'stubs' ?

Thanks,

Webminer.

changing the format of the datagrid
By AMKUMARAN on 8/31/2004
i have 2 rows table. the count of data is 240.

but i want to add to datagrid of 10 * 24 datagrid.

can anybody throw light on it.

thanks

Feedback about the Article
By me_shriram on 11/4/2004
Article is really good and practical.
It had solved many of my problems.
Thanks for the same.
-Shriram Nimbolkar.

Editable DataGrid
By amit_mane on 12/8/2004
I have generated the DataGrid Dynamically. It's editable abd uses paging(Normal n not Custom).
The problem is the events OnPageIndexChanged and OnUpdateVIew are not working.
DO you have any idea how to make 'em work programmatically

dynamic datagrid
By imjigu on 12/21/2004
this is really good and easy code to make datagrid dynamically. i m searching for last 10 days but when i got this , really it solve my problem.

Really Helped
By tusharkashyap on 12/22/2004
This article is very much helpful to do the dynamic programming. Thanx a lot

Copyright 2004 OdeToCode.com 


The Blogs
Subscribe to the OdeToCode blogs for the latest news, downloads, new articles, and quirky commentary.
New Articles
Databinding in Silverlight
This article will cover data binding features in Silverlight, including binding expressions, validation, converters, and binding modes.

The Standard LINQ Operators
This article will cover the standard LINQ operators provided by LINQ for filtering, grouping, joining, converting, projecting, and more.

C# 3.0 and LINQ
C# 3.0 introduced a number of new features for LINQ. In this article we'll examine the new features like extension methods, lambda expressions, anonymous types, and more.

Most Popular Articles
Table Variables In T-SQL
Table variables allow you to store a resultset in SQL Server without the overhead of declaring and cleaning up a temporary table. In this article, we will highlight the features and advantages of the table variable data type.

ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps
MasterPages are a great addition to the ASP.NET 2.0 feature set, but are not without their quirks. This article will highlight the common problems developers face with master pages, and provide tips and tricks to use master pages to their fullest potential.

AppSettings In web.config
In this article we will review a couple of pratices to keep your runtime configuration information flexible.

Contribute Code
Privacy
Consultancy