Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add TemplateField to a gridview in the code behind?

I have a DropDownList which has a list of tables. Under it there is GridView. Based on the table selected from the drop down list box, I will populate the GridView dynamically. Since the tables could have different column names, I need to create the template field for the GridView dynamically.

Following is my bind method. I have two problems:

  1. I couldn’t wrap the binding part in if (!IsPostBack) since the GridView is populated based on the selection of the DropDownList, so everytime I change the selection, the columns will be duplicated.
  2. And I don’t have any data, I think I need to set ItemTemplate of the tField (TemplateField), but how do I do that?

My bind method

private void BindGridView()
{
    DataSet ds = new DataSet();

    try
    {
        ds = …
        if (ds.Tables.Count > 0)
        {

            foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                TemplateField tField = new TemplateField();
                tField.HeaderText = dc.ColumnName;
                GridView2.Columns.Add(tField);
            }    

            GridView2.DataSource = ds.Tables[0];
            GridView2.DataBind();
        }
        else
        {
            …
        }
    }
    catch (Exception ex)
    {
        …    
    }
}
like image 851
GLP Avatar asked Dec 19 '13 21:12

GLP


1 Answers

There are various steps that should be taken care of:

STEP I:: Create a class inheriting the ITemplate interface. Override the method InstantiateIn() of the ITemplate interface.

STEP II:

Define a constructor for your class that takes a ListItemType object as its parameter.

STEP III::

If the Control being added to the container's ControlCollection has to be bound to some DataSource Column, then register the handler for the OnDataBinding event. When the event occurs, retrieve the text from the data source and assign it to your control. For Example, hyprLnk_DataBinding event is defined for Binding Data to your controls created inside ItemTemplate.

public class TemplateGenerator : ITemplate // Class inheriting ITemplate
{
    ListItemType type;
    string columnName;  

    public TemplateGenerator(ListItemType t, string cN)
    {           
       type = t;    
       columnName= cN;    
    }

    // Override InstantiateIn() method
    void ITemplate.InstantiateIn(System.Web.UI.Control container)
    {    
        switch (type)
        {
            case ListItemType.Item:    
               HyperLink hyprLnk = new HyperLink();
               hyprLnk.Target = "_blank"; //Optional.
               hyprLnk.DataBinding+=new EventHandler(hyprLnk_DataBinding);
               container.Controls.Add(hyprLnk);
            break;      
        }
    } 

    // The DataBinding event of your controls
    void hyprLnk_DataBinding(object sender, EventArgs e)
    {    
        HyperLink hyprlnk = (HyperLink)sender;
        GridViewRow container = (GridViewRow)hyprlnk.NamingContainer;
        object bindValue = DataBinder.Eval(container.DataItem,columnName);
        // Adding check in case Column allows null values
        if (bindValue != DBNull.Value) 
        {
            hyprlnk.Text = bindValue.ToString();
            hyprlnk.NavigateUrl = "http://www.google.com";
        }
    }
}

That's all. Above was just a sample to create ItemTemplate dynamically for GridView and add controls to the Item Template.

Now, Below is the function that will actually carry out the calls to create Template Columns dynamically. You can call this function when required for e.g. from your DropDownList event Handler.

protected void GenerateGridViewColumnsDynamically()
{
    // Create the TemplateField 
    TemplateField firstName = new TemplateField();
    firstName.HeaderText = "First_Name"; 
    firstName.ItemTemplate = new TemplateGenerator(ListItemType.Item, "FirstName");

    // Showing boundField example just for more context
    BoundField lastName = new BoundField();
    lastName.DataField = "LastName";
    lastName.HeaderText = "Last_Name";

    // Add the Columns now
    MyGridView.Columns.Add(firstName);
    MyGridView.Columns.Add(lastName);
}

NOTE:: FirstName and LastName are the Columns whose Names are passed to the constructor of your custom class: TemplateGenerator.

like image 157
R.C Avatar answered Nov 11 '22 02:11

R.C