我有 4 个复选框,每个复选框下面是一个 div。每个复选框负责显示或隐藏其下方的复选框。 例如:
<asp:CheckBox ID="CheckBox1" myDiv="divRegisteration" myText=" הרשמה - " runat="server" AutoPostBack="true" Font-Size="18px" Font-Bold="true" Text=" הרשמה - הצג" OnCheckedChanged="CheckBox_CheckedChanged"/>
<div id="divRegisteration" runat="server" visible="false">
复选框“CheckBox1”负责显示或隐藏 div“divRegisteration”,这在自定义属性“myDiv”中得到解决。
问题是,在后面的代码中,它没有找到属性“myDiv”:
if (((CheckBox)(sender)).Checked==true)
{
CheckBox chk = (CheckBox)(sender);
object div = FindControl(chk.Attributes["myDiv"]); //// it does not find myDiv, and therefore doesn't find the control so the program crashes.
HtmlGenericControl addressDiv = (HtmlGenericControl)(div);
addressDiv.Visible = true;
}
请您参考如下方法:
因为 Attributes 集合不是那样工作的:
Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.
如果你想拥有这样的属性,你需要创建你自己的自定义控件来拥有你想要的属性。或者,作为替代方案,创建一个承载单个 CheckBox 和相关联的 div 或诸如此类的用户控件——然后您可以在代码隐藏中通过 ID 引用一个相关的 div。实例化该控件的多个实例,一切顺利。
编辑:我的 WebForms-fu 有点生疏,但这里什么都没有。
控制类:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UserControlExample {
[ParseChildren(false)]
public class TogglePanel : UserControl {
private CheckBox cbToggleContent = new CheckBox();
private Panel pnlContentPlaceholder = new Panel();
public TogglePanel() {
Load += OnLoad;
}
public bool Checked { get; set; }
private void OnLoad(object sender, EventArgs eventArgs) {
Controls.Add(cbToggleContent);
Controls.Add(pnlContentPlaceholder);
if (!IsPostBack) {
cbToggleContent.Checked = Checked;
pnlContentPlaceholder.Visible = Checked;
}
cbToggleContent.AutoPostBack = true;
cbToggleContent.CheckedChanged += (s, args) => {
pnlContentPlaceholder.Visible = cbToggleContent.Checked;
};
}
protected override void AddParsedSubObject(object obj) {
pnlContentPlaceholder.Controls.Add((Control) obj);
}
}
}
及其用法:
<%@ Register TagPrefix="a" Namespace="UserControlExample" Assembly="UserControlExample" %>
<a:TogglePanel Checked="True" runat="server">
This stuff here will be shown or hidden based on the checkbox
</a:TogglePanel>
