HTML
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button runat="server" ID="show" OnClick="show_Click" Text="show"/>
<asp:Button runat="server" ID="add" OnClick="add_Click" Text="add new "/>
<div id="content" runat="server"></div>
</asp:Content>
码
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Checked);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
按钮add
在运行时添加了新的checkbox
。
然后我想通过按钮chb
show
但((CheckBox) content.FindControl("chb")).Checked
返回Null。
我想动态添加复选框,然后检查它们中的哪一个是真的。
答案 0 :(得分:0)
您的事件不会发生在页面的同一回发中 - 当您单击add
时,它会添加复选框,但页面执行完成后,页面将被发送到客户端并完成处理Click
事件。
当您单击show
按钮时,它是另一个回发,其中您的复选框尚未创建,因此它不存在。
要解决此问题,您可以选择以下几种方法:
1。
将复选框添加到设计器中的页面,并将其Visible
属性设置为false
。您可以保留add
按钮,但它实际上不会向页面添加复选框,只需将Visible
设置为true
即可将其显示。
2。
如果您确实想要动态添加复选框,则需要在每次执行页面时在其中一个页面事件处理程序中添加它(例如Load
)。这样做的方法是在单击add
时在视图状态或隐藏字段中保存值,并根据值,在后续回发中创建复选框。
protected void Page_Load (object sender, EventArgs e)
{
if ( IsPostBack )
{
if ( Session["chb"] != null )
CreateChb ();
}
}
protected void show_Click(object sender, EventArgs e)
{
Response.Write(((CheckBox) content.FindControl("chb")).Text);
}
protected void add_Click(object sender, EventArgs e)
{
Session["chk"] = true;
CreateChb ();
}
private void CreateChb ()
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
}
答案 1 :(得分:0)
这是因为回发后不会保留动态添加的控件。您可以通过向页面添加另一个按钮(没有单击事件处理程序)来轻松演示此操作。运行应用程序并单击“添加”按钮以创建复选框,然后单击新添加的按钮,复选将在回发后消失。
答案 2 :(得分:0)
好吧,我无法理解你想要实现的目标,但是;
protected void show_Click(object sender, EventArgs e)
{
Response.Write((Session["chb"] as CheckBox).Text);
}
protected void add_Click(object sender, EventArgs e)
{
CheckBox chb = new CheckBox();
chb.ID = "chb";
chb.Text = "chb";
content.Controls.Add(chb);
Session["chb"] = chb;
}