2009/04/13

GridView: Dynamically add cells

How to add a cell dynamically (or programmatically)? If you are going to add a cell without any control in it, here is the way:
e.Row.Cells[e.Row.Cells.Add(new TableCell())].Text = "Phone";
If you are going to add a cell with a server control in it (for example, TextBox), you should do like this:
//create a textbox control & set its attributes
TextBox oTB = new TextBox();
oTB.ID = "TextBox1";
oTB.AutoPostBack = true;
oTB.Attributes.Add("onfocus", "this.select();");
//attach the event
oTB.TextChanged += new EventHandler(TextBox_TextChanged);
//hey, the phone number here is just an example
oTB.Text = "1-800-551-1155";
//here is the key point
e.Row.Cells[e.Row.Cells.Add(new TableCell())].Controls.Add(oTB);
oTB = null;

PS: Add those codes to the GridView's RowDataBound event.

No comments:

Post a Comment