How Do I Make a TemplateField with Checkbox Through Code-behind?
Asked Answered
M

1

5

How can I add a template field with a checkbox to my DetailsView object through C# code-behind? I'm having trouble figuring it out from reading the asp.net code.

I already have the TemplateField and CheckBox object instantiated with values assigned to the properties. But when I use Fields.Add() the checkbox doesn't show-up.

    TemplateField tf_ForMalls = new TemplateField();
    tf_ForMalls.HeaderText = "For Malls";

    CheckBox chk_ForMalls = new CheckBox();
    chk_ForMalls.ID = "chkDelete";

    tf_ForMalls.ItemTemplate = chk_ForMalls as ITemplate;

    dv_SpotDetail.Fields.Add(tf_ForMalls);
Marieann answered 26/4, 2011 at 4:24 Comment(1)
Please post your code, what you have tried so farSpecht
K
10

You will need a custom class derived from ITemplate to get this working

public class MyTemplate : ITemplate
{
    #region ITemplate Members

    public void InstantiateIn(Control container)
    {
        CheckBox chk = new CheckBox();
        chk.ID = "chk";
        container.Controls.Add(chk);
    }

    #endregion
}

Then in the code

TemplateField tf = new TemplateField();
tf.ItemTemplate = new MyTemplate();
detvw.Fields.Add(tf);

You can have the constructor to pass in the parameters for 'control id' or specifying the ListItemType

Hope this helps

Kattegat answered 26/4, 2011 at 4:47 Comment(2)
I see, so I really do need to make a custom class for the template to work. I'll give this a go. Thank you. =)Marieann
@Erick, this is how templated control works - when you specify the template on markup, ASP.NET runtime creates a implementation of ITemplate for you. In case, you are going to create many template fields from code-behind, you may use a generic ITemplate implementation - see this article for the same - couldbedone.blogspot.com/2007/07/…Stefa

© 2022 - 2024 — McMap. All rights reserved.