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

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 class Item {   public int ID { get ; set ; }   public int Total { get ; set ; }   public Item()   {   }   public Item( int ID, int Total)   {     this .ID = ID; this .Total = Total;   }

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]; }

Get Tables and Columns Names by LINQ

Here I am explaining one of the tricks to get all table name list along with column of it from your DataContext. I am using the System.Data.Linq.Mapping.MetaModel to get information about tables and it have much more database related information. Following are the code to list all table name along with column from your DataContext. //DataContext object. DataClassesDataContext DB = new DataClassesDataContext ();         //String variable to stor html to render. string strHtmlToLoad = "" ;         //Heading strHtmlToLoad = "<-h2->Table Names<-/h2-><-ol->" ;         //Loop through tables add name to string foreach ( var mTable in DB.Mapping.GetTables()) { strHtmlToLoad += "<-li->" + mTable.TableName + "<-ul->" ; //Loop through table's columns add name to string foreach ( var mColumn in mTable.RowType.DataMembers) strHtmlToLoad += "<-li->