且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取CheckBox控件通过自定义在C#属性名称

更新时间:2022-10-15 08:08:56

这是你想要的吗?

 保护无效的Page_Load(对象发件人,EventArgs的发送)
{
    变种CB = FindControlByAttribute&所述; HtmlInputCheckBox>(this.PageATTR-ID中,111);}
公共ŧFindControlByAttribute< T>(CTL控制,串的attributeName,字符串的AttributeValue)其中T:HTMLControl时
{
    的foreach(在ctl.Controls控制C)
    {
        如果(c.GetType()== typeof运算(T)及及((T)C).Attributes [的attributeName] ==的AttributeValue)
        {
            返程(T)C;
        }
        变种CB = FindControlByAttribute< T>(三,的attributeName,的AttributeValue);
        如果(CB!= NULL)
            返回CB;
    }
    返回null;
}

I have a collection of checkbox some 40-50 nos and i have set a attribute 'attr-ID' for each checkbox which is a unique value ID in database. how can i get the control by attribute name in c# code. I want to check some of the checkbox according to dB values on page load event.

 <input type="checkbox" id="rdCervical" attr-ID='111' runat='server' />

Is this what you want?

protected void Page_Load(object sender, EventArgs e)
{
    var cb = FindControlByAttribute<HtmlInputCheckBox>(this.Page, "attr-ID", "111");

}
public T FindControlByAttribute<T>(Control ctl, string attributeName, string attributeValue) where T : HtmlControl
{
    foreach (Control c in ctl.Controls)
    {
        if (c.GetType() == typeof(T) && ((T)c).Attributes[attributeName]==attributeValue)
        {
            return (T) c;
        }
        var cb= FindControlByAttribute<T>(c, attributeName, attributeValue);
        if (cb != null)
            return cb;
    }
    return null;
}