I'm dynamically creating a GridView bound to a datatable using custom template columns using the following method:
Expand|Select|Wrap|Line Numbers
- protected void ShowGrid(DataTable dt)
- {
- int i;
- int j;
- for( i = 0; i < dt.Columns.Count; i++)
- {
- TemplateField tf = new TemplateField();
- tf.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dt.Columns[i].ColumnName);
- for(j = 0; j < dt.Rows.Count; j++)
- {
- tf.ItemTemplate = new GridViewTemplate(ListItemType.EditItem, dt.Columns[i].ColumnName + j.ToString(),GridView1.Rows[i].Cells[j].Controls[0].ToString());
- }
- GridView1.Columns.Add(tf);
- }
- }
Expand|Select|Wrap|Line Numbers
- switch (templateType)
- {
- ...
- case ListItemType.EditItem:
- TextBox tb = new TextBox();
- tb.ID = columnName;
- if (columnName.Contains("Date"))
- {
- CalendarExtender cal = new CalendarExtender();
- cal.TargetControlID = tb.ID;
- cal.Format = "MM/dd/yy";
- cal.PopupPosition = CalendarPosition.BottomLeft;
- tb.Text = value;
- container.Controls.Add(cal);
- container.Controls.Add(tb);
- }
- else if (columnName.Contains("Usage"))
- {
- Label l = new Label();
- l.Text = " kWh";
- tb.Width = 150;
- tb.Text = value;
- container.Controls.Add(tb);
- container.Controls.Add(l);
- }
- else if (columnName.Contains("Cost"))
- {
- tb.Text = value;
- container.Controls.Add(tb);
- }
- break;
Expand|Select|Wrap|Line Numbers
- protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- TextBox txt;
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- for (int i = 0; i < e.Row.Cells.Count; i++)
- {
- for (int j = 0; j < e.Row.Cells[i].Controls.Count; j++)
- {
- if (e.Row.Cells[i].Controls[j] is TextBox)
- {
- txt = (TextBox)e.Row.Cells[i].Controls[j];
- if (txt != null && Page.IsPostBack)
- {
- txt.Text = Request.Form[txt.UniqueID];
- }
- }
- }
- }
- }
- }