// Create our template column. TemplateDataField templateField1 = new TemplateDataField(true); templateField1.Key = "TemplateField1"; templateField1.Header.Text = "Template Column"; templateField1.ItemTemplate.InstantiateIn(LiteralDisplayName); WebDataGrid1.Columns.Add(templateField1);
divHeader.Controls.Add(LiteralHeader); //divDisplayName.Controls.Add(LiteralDisplayName); divDisplayName.Controls.Add(WebDataGrid1);
Hello,
Based on the code snippet you provided, the approach you've taken is the right one for adding template columns programmatically. Here's what one should do, following the procedure described in "Using Item Template" topic:
private class CustomItemTemplate : ITemplate { public void InstantiateIn(Control container) { var dataItem = ((DataRowView)((TemplateContainer)container).DataItem); Label idLabel = new Label(); idLabel.Text = dataItem["ID"].ToString(); Label detailsLabel = new Label(); detailsLabel.Text = dataItem["Name"].ToString() + " " + dataItem["Description"].ToString(); container.Controls.Add(idLabel); container.Controls.Add(new LiteralControl("<br />")); container.Controls.Add(detailsLabel); } }
protected void Page_Load(object sender, EventArgs e) { TemplateDataField field1 = new TemplateDataField(); field1.Key = "TemplateColumn1"; field1.Header.Text = "ID"; WebDataGrid1.Columns.Add(field1); field1.ItemTemplate = new CustomItemTemplate(); WebDataGrid1.DataSource = populateGrid(); if (!Page.IsPostBack) { WebDataGrid1.DataBind(); } }
This is the approach I implemented in the sample application I am attaching for your reference. Please, review it and let us know if you need further assistance on the matter.
2437.WebDataGridItemTemplate.zip