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

Viewed 26826

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)
    {
        …    
    }
}
2 Answers
Related