Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
15
how to add control to dynamic template field in webdatagrid from server side
posted

// 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);

  • 3480
    Offline posted

    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:

    1. First, create a custom template as follows:

    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);
            }
        }
    

    1. Then in the page load event, create a template field and assign its ItemTemplate to an instance of CustomItemTemplate:

    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