Saturday, February 28, 2009

Add columns in GridView dynamically

Create a class with GridViewTemplate Name, copy and paste the the code in between // GridViewTemplate class - starts and // GridViewTemplate class - ends in GridViewTemplate class

// GridViewTemplate class - starts
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string dataType;

public GridViewTemplate(DataControlRowType type, string colname, string DataType)
{
templateType = type;
columnName = colname;
dataType = DataType;
}

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:
if (!columnName.Equals("Name"))
{
Button bl = new Button();
bl.DataBinding += new EventHandler(this.bl_DataBinding);
container.Controls.Add(bl);
}
else
{
Label l = new Label();
l.DataBinding += new EventHandler(this.l_DataBinding);
container.Controls.Add(l);
}

break;
default:
break;
}
}


private void bl_DataBinding(Object sender, EventArgs e)
{
Button bl = (Button)sender;
GridViewRow row = (GridViewRow)bl.NamingContainer;
bl.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}

private void l_DataBinding(Object sender, EventArgs e)
{
Label l = (Label)sender;
// get the containing row
GridViewRow row = (GridViewRow)l.NamingContainer;
// get the raw data value and make it pretty
l.Text = DataBinder.Eval(row.DataItem, columnName).ToString();
}
}

// GridViewTemplate class - ends

Now Add a GridView control in the aspx with grdMain name, put the below code on page load of aspx page

grdMain.Columns.Clear();
DataTable dtReport = new DataTable();
DataColumn col = new DataColumn("test1");
DataColumn col1 = new DataColumn("test2");
DataColumn col2 = new DataColumn("test3");

dtReport.Columns.Add(col);
dtReport.Columns.Add(col1);
dtReport.Columns.Add(col2);

DataRow dr1 = dtReport.NewRow();
dr1["test1"] = "One";
dr1["test2"] = "One1";
dr1["test3"] = "One2";

dtReport.Rows.Add(dr1);


for (int i = 0; i < dtReport.Columns.Count; i++)
{
TemplateField tf = new TemplateField();
tf.ItemTemplate =
new GridViewTemplate(DataControlRowType.DataRow,
dtReport.Columns[i].ColumnName,
dtReport.Columns[i].DataType.Name);
tf.HeaderTemplate =
new GridViewTemplate(DataControlRowType.Header,
dtReport.Columns[i].ColumnName,
dtReport.Columns[i].DataType.Name);
grdMain.Columns.Add(tf);
}

// bind and display the data
grdMain.DataSource = dtReport;
grdMain.DataBind();
grdMain.Visible = true;

Compile and run the application.

Happy Coding

No comments:

Site Meter