Get checkbox Controls by custom attribute name in C #

I have a set of flags about 40-50 ns in size, and I set the 'attr-ID' attribute for each flag, which is a unique identifier for the value in the database. how can i get the control by attribute name in c # code. I want to check some checkboxes according to dB values ​​at page load event.

<input type="checkbox" id="rdCervical" attr-ID='111' runat='server' /> 
+4
source share
2 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; } 
+6
source
 if (rdCervical.Attributes["attr-ID"] != null) { string id = rdCervical.Attributes["attr-ID"]; rdCervical.Checked = true; } 

I assume that you add checkboxes programmatically. In this case, create the container <div id="checkContainer" runat="server"></div> and put all your checkboxes in it. Then just use checkContainer.InnerHtml and checkContainer.InnerHtml this code with this library . Then you can easily use the library API to search for elements by attribute, I think the method was SelectNodes

Without this library, there is no easy way to navigate HTML elements from code.

+5
source

Source: https://habr.com/ru/post/1387567/


All Articles