Saturday, April 16, 2005

Adding a column dynamically to the datagrid control

Sometimes we need to add a dynamic column to a datagrid. We can also add the dynamic control to the datagrid control.
Here is the C# code to achieve that:


private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
OleDbDataAdapter ad = new OleDbDataAdapter("SELECT * FROM Person",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Person");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}


private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
{
TextBox t = new TextBox();
t.ID = "ada";
t.Text = "This is a test";
e.Item.Controls[0].Controls.Add(t);
}


}


}

No comments: