如何通过编程在ASP.NET中使用复选框定义templatefield? [英] How can I define templatefield with check box in ASP.NET with programming?

查看:68
本文介绍了如何通过编程在ASP.NET中使用复选框定义templatefield?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在asp.net中使用gridview上的复选框定义一个带有编程的模板字段。

像这样:

 TemplateField tf =  new  TemplateField(); 
tf.ItemTemplate = new System.Web.UI.WebControls.CheckBox();
gridView1.Columns.Add(tf);





我尝试过:



但出现此错误:

无法隐式转换'System.Web.UI.WebControls.CheckBox'到'System.Web.UI.ITemplate'。

解决方案

ItemTemplate 需求是一个实现的类的实例 ITemplate 界面 [ ^ ], NOT 一个控件实例。它需要为父控件中的每个数据项创建一个新的控件实例。

  public   class  CheckBoxTemplate:ITemplate 
{
public void InstantiateIn(控件容器)
{
CheckBox child = new CheckBox();
child.DataBinding + = BindData;
container.Controls.Add(child);
}

私有 void BindData( object sender,EventArgs e)
{
CheckBox child =(CheckBox)sender;
IDataItemContainer container =(IDataItemContainer)child.NamingContainer;
child.Checked = DataBinder.Eval(container.DataItem, 您的物业名称 );
}
}

...

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



ITemplate.InstantiateIn(Control)方法(System.Web.UI)| Microsoft Docs [ ^ ]


I want to define a templatefield with checkbox on gridview in asp.net with programming.
like this:

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'.

解决方案

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.

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[^]


这篇关于如何通过编程在ASP.NET中使用复选框定义templatefield?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆