Skip to main content

Dynamic columns in Gridview

There are many types of column field are are available for grid view like
  • BoundField
  • ButtonField
  • CheckBoxField
  • CommandField
  • HyperLinkField
  • ImageField
  • TemplateField
Here I explain how to add dynamically Bound Field and then Template Field into grid view. First we look how to add Bound Field into Grid view and then Template Field.

First of all make your AutoGenerateColumns property to false.

Prepare your data source which will you going bind with grid view. it will be Data Table or Generic List of class type or structure type any thing or Table Class of your Linq dbml data contexts class.

Here we are going to use Data Table as follow.

DataTable dt = new DataTable("ItemMaster");

dt.Columns.Add(new DataColumn("ItemId",typeof(Int32)));
dt.Columns.Add(new DataColumn("ItemName", typeof(String)));
dt.Columns.Add(new DataColumn("Price", typeof(Decimal)));

for (int i = 0; i < 10; i++)
{
     DataRow dr = dt.NewRow();
     dr[0] = i + 1;
     dr[1] = "Name " + i.ToString();
     dr[2] = i * 0.5 + 1;
     dt.Rows.Add(dr);
}

For each column of table we have to add one BoundField into gridview following is code for that

foreach (DataColumn dc in dt.Columns)
{
     BoundField bf = new BoundField();
     bf.DataField = dc.ColumnName;
     bf.HeaderText = dc.ColumnName;
     GridView1.Columns.Add(bf);
}

Now you grid view is ready to bind DataTable.

GridView1.DataSource = dt;
GridView1.DataBind();

This type of dynamic generated column is useful when we want custom css and style depend on some logic. and we want to show hide some column dynamically.

To add Template Field dynamically you have to create one class which inherit ITemplate interface. Here in example we create one hyperlink template field class which inherit ITemplate interface then we bind that field to our grid view using data table.



public class HyperLinkTemplate : ITemplate
{
    private DataControlRowType TemplateType;
    private string ColumnName;
    private string NavigateUrl;
    private string Text;

    public HyperLinkTemplate(DataControlRowType TemplateType, string ColumnName, string NavigateUrl, string Text)
    {
        this.TemplateType = TemplateType;
        this.ColumnName = ColumnName;
        this.NavigateUrl = NavigateUrl;
        this.Text = Text;
    }

    public void InstantiateIn(System.Web.UI.Control container)
    {
        switch (TemplateType)
        {
            case DataControlRowType.Header:
                Literal lc = new Literal();
                lc.Text = ColumnName;
                container.Controls.Add(lc);
                break;
            case DataControlRowType.DataRow:
                HyperLink objHyperLink = new HyperLink();
                objHyperLink.Target = "_blank";
                objHyperLink.DataBinding += new EventHandler(objHyperLink_DataBinding);
                container.Controls.Add(objHyperLink);
                break;
            default:
                break;
        }
    }

    void objHyperLink_DataBinding(object sender, EventArgs e)
    {
        HyperLink objHyperLink = sender as HyperLink;
        GridViewRow row = (GridViewRow)objHyperLink.NamingContainer;
        objHyperLink.NavigateUrl = NavigateUrl;
        objHyperLink.Text = DataBinder.Eval(row.DataItem, Text).ToString();
    }
}

To bind this HyperLinkTemplate to oure grid view use following code. Here we bind Item name column to this template field with editpage.aspx url. this code display both boud field and template field adding.



foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName != "ItemName")
{
BoundField bf = new BoundField();
bf.DataField = dc.ColumnName;
bf.HeaderText = dc.ColumnName;
GridView1.Columns.Add(bf);
}
else
{
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new HyperLinkTemplate(DataControlRowType.Header, dc.ColumnName, "", "");
tf.ItemTemplate = new HyperLinkTemplate(DataControlRowType.DataRow, dc.ColumnName, "~/editpage.aspx", dc.ColumnName);
GridView1.Columns.Add(tf);
}
}





Popular posts from this blog

SqlConnection from ObjectContext.Connection

Following is C# code to get the  SqlConnection from ObjectContext.Connection . This is usefully to run dynamically created query using ADO.NET using connection string specified into the EDMX ObjectContext object. C# Code Example : using ( EntityContext context = new EntityContext ()) { EntityConnection ec = ( EntityConnection )context.Connection; SqlConnection sc = ( SqlConnection )ec.StoreConnection; SqlDataAdapter da = new SqlDataAdapter (strQuery, sc); DataSet ds = new DataSet (); da.Fill(ds); return ds.Tables[0]; }

LINQ union with group by

In my recent development activity with LINQ query, I need to get the some of user points from tow different tables where user's points are based on some activities. There are many users who are into one table but not in another table and some are in both table. For example tables having data like this Table 1 UserID   Points 1           10 2           20 Table 2 UserID    Points 2           20 3           30 Result should be UserID    Points 1           10 2           40 3           30 I try to get this result with LINQ query using joins and group by samples from the web. I had googling to get something useful but dont get any success. So I try with new logic and here it is, I think it will help full to other also. Example Item class to use public cla...

Google Analytic Dashboard Controls

"Google Analytic Dashboard Controls" is costume controls library which contain ASP.NET costume controls which generate different types of charts like Google analytic dashboard using Google analytic data export api. Its include following controls. Visitors overviews Word map overview Traffic source overview Content overview Followings are the images of the resulting graphs using them Visitors Overview Traffic Source Overview Word Map Overview Content Visits Overview To use this controls into your ASP.NET projects follow the below steps. 1. Download "Google Analytics Desbord Controls.dll" 2. Add reference of "Google Analytics Desbord Controls.dll" to your project. 3. In toolbox add controls by Right Click -> Choose Items -> browse dll. 4. Now Drag and drop control to your .aspx file. 5. Set Properties GAEmailAddress to your Google Analytic account email id, GAPassword to password , GAProfileId ...