简体   繁体   English

如何通过代码隐藏使复选框创建TemplateField?

[英]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? 如何通过C#代码隐藏向我的DetailsView对象添加带有复选框的模板字段? I'm having trouble figuring it out from reading the asp.net code. 我在阅读asp.net代码时遇到了麻烦。

I already have the TemplateField and CheckBox object instantiated with values assigned to the properties. 我已经使用分配给属性的值实例化了TemplateField和CheckBox对象。 But when I use Fields.Add() the checkbox doesn't show-up. 但是当我使用Fields.Add()时,复选框不显示。

    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 您将需要一个从ITemplate派生的自定义类来实现此功能

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 您可以让构造函数传入“control id”的参数或指定ListItemType

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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