【问题标题】:get checkbox Controls by custom attribute name in C#在 C# 中通过自定义属性名称获取复选框控件
【发布时间】:2011-12-22 13:49:30
【问题描述】:

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

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

【问题讨论】:

  • 它们有 runat="server" 属性还是简单的 html 元素?
  • HTML5 允许以 data- 开头的属性,但对于其他任何事情,我认为您必须编写自己的解析器。
  • 是的,他们有运行服务器,但我无法识别 c# 中的控件 ID
  • 如果他们有 runat="=server" 他们应该在后面的代码中可用。它们是否位于自定义控件中?你能发布更多的容器代码吗?
  • 它是一个普通的 html 控件,但我有很多复选框,并且在服务器端识别每个复选框 id 必须检查每个 id 和我不需要的属性值。因此,如果有某种方法可以检查属性并对其进行检查。

标签: c# asp.net html


【解决方案1】:

这是你想要的吗?

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

【讨论】:

  • 他用的不是服务器控件,而是html控件HtmlInputCheckBox
  • @Arion : 你能在你的函数中指定一个区域吗意味着在指定的 div 中找到一个控件,就像我在一个 div 中有大约 50 个复选框,它们的 id ='dvCheckboxes'。我使用了你的功能,但我总是得到空值。感谢您的帖子.. 并请帮助
  • @deepu:此函数循环页面上的所有控件。如果有一个具有属性 attr-ID 的控件并且其值为 111,它将返回它。如果您有一个带有复选框的 div,请查看它是否具有 runat="server"。然后您可以在此函数中使用该控件,它将返回复选框
【解决方案2】:
if (rdCervical.Attributes["attr-ID"] != null)
{
      string id = rdCervical.Attributes["attr-ID"];
      rdCervical.Checked = true;
}

我假设您正在以编程方式添加复选框。在这种情况下,创建一个容器 &lt;div id="checkContainer" runat="server"&gt;&lt;/div&gt; 并将所有复选框放入其中。然后只需使用checkContainer.InnerHtml 并使用this library 解析该代码。然后您可以轻松地使用库 API 按属性查找元素,我认为方法是 SelectNodes

如果没有这个库,就很难从代码中浏览 HTML 元素。

【讨论】:

  • 复选框 id 不能被选中,因为我有很多复选框我有所有使用它的复选框的共同属性我需要确定哪个复选框需要被选中
  • 我假设您正在以编程方式添加复选框。在这种情况下,创建一个容器 &lt;div id="checkContainer" runat="server"&gt;&lt;/div&gt; 并将所有复选框放入其中。然后只需使用checkContainer.InnerHtml 并使用此库解析该代码。然后,您可以轻松地使用库 API 按属性查找元素。 htmlagilitypack.codeplex.com
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 2016-04-06
  • 2015-05-08
  • 2013-02-11
相关资源
最近更新 更多