Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get checkbox Controls by custom attribute name in C#

Tags:

html

c#

asp.net

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' />
like image 760
deepu Avatar asked Dec 21 '22 04:12

deepu


1 Answers

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;
}
like image 129
Arion Avatar answered Dec 23 '22 18:12

Arion