public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
}
}
我想要事件btn_click&amp; btn2_click来回复每个帖子..当我点击以编程方式创建的按钮时,它会在每次回发后消失并且其事件不会触发(btn2_click)。我知道我可以在回发中生成按钮..但我不想这样做!我想知道如何更新占位符的状态...以便显示唯一的按钮,并在Generate5Controls(PlaceHolder placeH)中生成的5个按钮消失。
我可以使用bool Viewstate来阻止这种generate.Generate5Controls(PlaceHolder1);从执行..
但问题是如何让以编程方式生成的按钮出现??
答案 0 :(得分:1)
您应该在每个PostBack上生成控件,或者您可以生成一次控件,保存在会话中并在page_load事件的会话中添加生成的控件。
protected void Page_Load(object sender, EventArgs e)
{
if(Session["GeneratedButtons"] == null)
{
GenerateButtons generate = new GenerateButtons();
generate.Generate5Controls(PlaceHolder1);
}
else
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
foreach(Control oneControl in generatedControls)
{
PlaceHolder1.Controls.Add(oneControl);
}
}
}
class GenerateButtons
{
PlaceHolder placeHolder;
public void Generate5Controls(PlaceHolder placeH)
{
placeHolder = placeH;
List<Control> generatedControls = new List<Control>();
for (int i = 0; i < 5; i++)
{
Button newBtn = new Button();
newBtn.Click += btn_Click;
newBtn.Text = "PageLoadButton Created. Number: "+i;
placeHolder.Controls.Add(newBtn);
AddControlToSession(newBtn);
}
}
public void btn_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn_click";
newBTN.Click += btn2_Click;
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
public void btn2_Click(object sender, EventArgs e)
{
Button newBTN = new Button();
newBTN.Text = "A New Button was added by the button event btn2_click";
placeHolder.Controls.Add(newBTN);
AddControlToSession(newBtn);
}
private void AddControlToSession(Control ctrl)
{
List<Control> generatedControls = Session["GeneratedButtons"] as List<Control>;
if(generatedControls == null)
{
generatedControls = new List<Control>();
}
generatedControls.Add(ctrl);
Session["GeneratedButtons"] = generatedControls;
}
}