在c#中通过自定义属性名获取复选框控件
本文关键字:获取 复选框 控件 自定义属性 | 更新日期: 2023-09-27 18:18:32
我有一些40-50 no复选框的集合,我已经设置了一个属性' attri -ID'为每个复选框,这是在数据库中的唯一值ID。我如何在c#代码中通过属性名获得控件。我想根据页面加载事件的dB值检查一些复选框。
<input type="checkbox" id="rdCervical" attr-ID='111' runat='server' />
这是你想要的吗?
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 (rdCervical.Attributes["attr-ID"] != null)
{
string id = rdCervical.Attributes["attr-ID"];
rdCervical.Checked = true;
}
我假设您正在以编程方式添加复选框。在这种情况下,创建一个容器<div id="checkContainer" runat="server"></div>
,并将所有复选框放入其中。然后使用checkContainer.InnerHtml
并使用这个库解析该代码。然后,您可以轻松地使用库API按属性查找元素,我认为该方法是SelectNodes
如果没有这个库,从代码中导航HTML元素就不容易。