Click here to Skip to main content
15,899,025 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to define a templatefield with checkbox on gridview in asp.net with programming.
like this:
C#
TemplateField tf = new TemplateField();
tf.ItemTemplate = new System.Web.UI.WebControls.CheckBox();
gridView1.Columns.Add(tf);


What I have tried:

but this error appear:
cannot implicitly convert 'System.Web.UI.WebControls.CheckBox' to 'System.Web.UI.ITemplate'.
Posted
Updated 5-Sep-18 8:57am
v2

1 solution

The ItemTemplate needs to be an instance of a class which implements the ITemplate interface[^], NOT a control instance. It will need to create a new instance of the control for each data item in the parent control.
C#
public class CheckBoxTemplate : ITemplate
{
    public void InstantiateIn(Control container)
    {
        CheckBox child = new CheckBox();
        child.DataBinding += BindData;
        container.Controls.Add(child);
    }
    
    private void BindData(object sender, EventArgs e)
    {
        CheckBox child = (CheckBox)sender;
        IDataItemContainer container = (IDataItemContainer)child.NamingContainer;
        child.Checked = DataBinder.Eval(container.DataItem, "Your Property Name Here");
    }
}

...

TemplateField tf = new TemplateField();
tf.ItemTemplate = new CheckBoxTemplate();
gridView1.Columns.Add(tf);

ITemplate.InstantiateIn(Control) Method (System.Web.UI) | Microsoft Docs[^]
 
Share this answer
 
Comments
Member 10604657 5-Sep-18 15:28pm    
Thanks a lot
I tried and get correct result.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900