C# 在C中通过自定义属性名获取复选框控件#

C# 在C中通过自定义属性名获取复选框控件#,c#,asp.net,html,C#,Asp.net,Html,我有一个40-50个复选框的集合,我为每个复选框设置了一个属性“attr ID”,它是数据库中唯一的值ID。如何在c#代码中通过属性名获取控件。我想根据页面加载事件上的dB值选中一些复选框 <input type="checkbox" id="rdCervical" attr-ID='111' runat='server' /> 我假设您是通过编程方式添加复选框的。在这种情况下,制作一个容器,并将所有复选框放在其中。然后只需使用checkContainer.InnerHtml

我有一个40-50个复选框的集合,我为每个复选框设置了一个属性“attr ID”,它是数据库中唯一的值ID。如何在c#代码中通过属性名获取控件。我想根据页面加载事件上的dB值选中一些复选框

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


我假设您是通过编程方式添加复选框的。在这种情况下,制作一个容器
,并将所有复选框放在其中。然后只需使用
checkContainer.InnerHtml
并使用解析代码即可。然后,您可以轻松地使用库API按属性查找元素,我认为方法是
SelectNodes

没有这个库,就无法从代码中轻松浏览HTML元素。

这就是您想要的吗

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;
}
受保护的无效页面加载(对象发送方,事件参数e)
{
var cb=FindControlByAttribute(this.Page,“attr ID”,“111”);
}
公共T FindControlByAttribute(控制ctl、字符串attributeName、字符串attributeValue),其中T:HtmlControl
{
foreach(控制中的控制c)
{
if(c.GetType()==typeof(T)和((T)c).Attributes[attributeName]==attributeValue)
{
返回(T)c;
}
var cb=FindControlByAttribute(c,attributeName,attributeValue);
如果(cb!=null)
返回cb;
}
返回null;
}

它们有runat=“server”属性还是简单的html元素?HTML5允许以
数据-
开头的属性,但对于其他任何东西,我想你都必须编写自己的解析器。是的,它们有runat=“server”,但我无法在c中识别控件id,如果它们有runat=“=server”它们应该在代码隐藏中可用。它们是否位于自定义控件中?你可以发布一些容器的代码吗?这是一个普通的html控件,但我有很多复选框,在服务器端识别每个复选框id必须检查每个id和我不需要的属性值。因此,如果有某种方法可以检查属性并将其选中。他没有使用服务器控件,而是使用html控件
HtmlInputCheckBox
@Arion:你能在函数中指定一个区域吗?这意味着在指定的div中找到一个控件,就像我在一个div中有50个复选框,其中有一个id='dvcheckbox'。我使用了你的函数,但我总是得到空值。谢谢你的来信。。请help@deepu:此函数循环页面上的所有控件。如果有一个属性为attr ID且值为111的控件,它将返回该属性。如果您有一个带有复选框的div,请参见以使其具有runat=“server”。然后,您可以在此函数中使用该控件,它将返回复选框无法选中复选框id,因为我有许多复选框我对所有复选框都有一个公共属性使用它我需要确定需要选中哪个复选框我假设您是通过编程方式添加复选框的。在这种情况下,制作一个容器
,并将所有复选框放在其中。然后只需使用
checkContainer.InnerHtml
并用这个库解析代码。然后可以轻松地使用库API按属性查找元素。
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;
}