这是向页面连续添加按钮的示例。每个新创建的按钮也可以向页面添加另一个按钮。可以与所有类型的控件一起使用。另外,您还必须在每个PostBack上重新创建动态控件,否则它们及其内容将丢失。
protected void Page_Load(object sender, EventArgs e){ //set the initial number of buttons int buttonCount = 1; //check if the viewstate with the buttoncount already exists (= postback) if (ViewState["buttonCount"] != null) { //convert the viewstate back to an integer buttonCount = Convert.ToInt32(ViewState["buttonCount"]); } else { ViewState["buttonCount"] = buttonCount; } //create the required number of buttons for (int i = 1; i <= buttonCount; i++) { createButton(i); }}private void createButton(int cnt){ //create a new button control Button button = new Button(); button.Text = "Add another Button (" + cnt + ")"; //add the correct method to the button button.Click += DynamicButton_Click; //another control, in this case a literal Literal literal = new Literal(); literal.Text = "<br>"; //add the button and literal to the placeholder PlaceHolder1.Controls.Add(button); PlaceHolder1.Controls.Add(literal);}protected void DynamicButton_Click(object sender, EventArgs e){ //get the current number of buttons int buttonCount = Convert.ToInt32(ViewState["buttonCount"]) + 1; //create another button createButton(buttonCount); //set the new button count into the viewstate ViewState["buttonCount"] = buttonCount;}更新
您还可以将a委托
Command给按钮而不是委托给按钮
Click,并以此将变量和按钮一起发送为
CommandArgument。您将不得不稍微更改按钮的创建。
//add the correct method to the buttonbutton.Command += DynamicButton_Command;//now you can also add an argument to the buttonbutton.CommandArgument = "Create Hazard";
您还需要其他方法来处理按钮单击。
protected void DynamicButton_Command(object sender, CommandEventArgs e){ //get the current number of buttons int buttonCount = Convert.ToInt32(ViewState["buttonCount"]) + 1; //create another button createButton(buttonCount); //set the new button count into the viewstate ViewState["buttonCount"] = buttonCount; //get the commandargument from the button string buttonArgument = e.CommandArgument.ToString();}


