您必须在每次回发时重新创建动态控件,它们不会神奇地重新出现,因为每个请求都是Page
该类的新实例。
请参阅我之前关于此主题的帖子,它使用的是用户控件,但想法是一样的。
还有一个
您必须在 Page_Load 之前添加控件
我通常在被覆盖的情况下这样做,CreateChildControls
但有些人使用Page_Init
.
看这篇文章
更新
这是一种非常简单的动态添加复选框的方法,在单击按钮时保留状态/值。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="ph"></asp:PlaceHolder>
<asp:Button OnClick="btn_Click" runat="server" ID="btn" Text="Click Me" />
<asp:Label runat="server" ID="lbl"></asp:Label>
</form>
</body>
</html>
然后代码后面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test : Page
{
private CheckBox MyCheckBox { get; set; }
protected override void CreateChildControls()
{
this.MyCheckBox = new CheckBox() { Checked = true };
this.ph.Controls.Add(this.MyCheckBox);
base.CreateChildControls();
}
protected void btn_Click(object sender, EventArgs e)
{
var someValue = this.MyCheckBox.Checked;
this.lbl.Text = someValue ? "Checked" : "Not Checked";
}
}