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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With