简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM