2011-12-22 75 views
4

我有一个复选框的集合一些40-50 nos,我已经为每个复选框设置属性'attr-ID',这是数据库中唯一的值标识。我怎么能通过属性名称控制在C#代码。我想根据页面加载事件的dB值检查一些复选框。获取复选框通过在C#中的自定义属性名称控制

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

他们有runat =“server”属性还是他们简单的html元素? – 2011-12-22 13:54:44

+0

HTML5允许以'data-'开头的属性,但是对于其他任何我认为您必须编写自己的解析器的信息,恐怕。 – 2011-12-22 13:55:14

+0

是的,他们有runat服务器,但我不能在c中识别控制ID# – deepu 2011-12-22 14:00:10

回答

5
if (rdCervical.Attributes["attr-ID"] != null) 
{ 
     string id = rdCervical.Attributes["attr-ID"]; 
     rdCervical.Checked = true; 
} 

我假设你是编程添加的复选框。在这种情况下,制作一个容器<div id="checkContainer" runat="server"></div>并将其中的所有复选框放入其中。然后,只需使用checkContainer.InnerHtml并用this library解析该代码即可。然后,您可以很容易地使用库API按属性查找元素,我认为该方法是SelectNodes

没有这个库,没有简单的方法来浏览代码中的HTML元素。

+0

复选框ID无法检查,因为我有很多复选框我有一个共同属性的所有复选框使用它我需要确定哪个复选框需要检查 – deepu 2011-12-23 04:06:21

+0

我假设你正在以编程方式添加复选框。在这种情况下,制作一个容器'

'并将其所有复选框放入其中。然后使用'checkContainer.InnerHtml'并用这个库解析这些代码。然后,您可以轻松使用库API按属性查找元素。 http://htmlagilitypack.codeplex.com/ – 2011-12-23 04:10:45

6

这是你想要的吗?

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; 
} 
+0

他没有使用服务器控件,但html控件'HtmlInputCheckBox' – 2011-12-22 14:33:46

+1

这是他想要的吗? – Arion 2011-12-22 14:43:01

+0

im使用html控件而不是服务器控件... – deepu 2011-12-23 04:07:22