如何动态生成TextBox控件。
如何通过单击按钮在运行时动态生成TextBox控件? 对于每个按钮单击,我想创建一个TextBox控件以及相应的动态标签。 我想在ASP.NET中使用C#语言执行此操作。
TextBox txt = new TextBox(); txt.ID = "textBox1"; txt.Text = "helloo"; form1.Controls.Add(txt); Label lbl = new Label(); lbl.Text = "I am a label"; form1.Controls.Add(lbl);
以下将创建控件:
var newTextbox = new Textbox(); var newLabel = new Label();
然后,您可以设置所需的属性等。
然后找到页面上的某个位置添加它们,比如你有一个名为panel1的面板,然后执行以下操作:
panel1.Controls.Add(newTextbox); panel1.Controls.Add(newLabel);
但是,在回发后执行此操作无效 – 您需要在回发时自行重新创建动态控件。
假设您有以下页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
执行回发时,只会为您生成上一页中定义的控件。 您动态添加的控件需要由您重新创建(例如在Page_Load中)。
要做到这一点,最简单的方法是记住您在视图状态中添加的控件总数,然后在发生回发时添加许多控件。
以下内容应该让您入门:
using System; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Add any controls that have been previously added dynamically for (int i = 0; i < TotalNumberAdded; ++i) { AddControls(i + 1); } // Attach the event handler to the button Button1.Click += new EventHandler(Button1_Click); } void Button1_Click(object sender, EventArgs e) { // Increase the number added and add the new label and textbox TotalNumberAdded++; AddControls(TotalNumberAdded); } private void AddControls(int controlNumber) { var newPanel = new Panel(); var newLabel = new Label(); var newTextbox = new TextBox(); // textbox needs a unique id to maintain state information newTextbox.ID = "TextBox_" + controlNumber; newLabel.Text = "New Label"; // add the label and textbox to the panel, then add the panel to the form newPanel.Controls.Add(newLabel); newPanel.Controls.Add(newTextbox); form1.Controls.Add(newPanel); } protected int TotalNumberAdded { get { return (int)(ViewState["TotalNumberAdded"] ?? 0); } set { ViewState["TotalNumberAdded"] = value; } } } }
要按要求添加多个控件,请使用for循环:
for (int i = 0; i < 2; ) { TextBox textBox = new TextBox(); textBox.Text = "Hi"; textBox.Name = "textBox" + i.ToString(); form2.Controls.Add(textBox); }
但控件(文本框)重叠。 你需要组织他们的位置。
编辑:例如
TextBox txt = new TextBox(); txt.Location = new Point(500, 100);
下面的代码显示了如何根据下拉列表中选择的值打印标签和文本框。 使用两个占位符,以便它们可以适当地放置在两个不同的表格分区中
int numlabels = System.Convert.ToInt32(ddlNumOfVolunteers.SelectedItem.Text); for (int i = 1; i <= numlabels; i++) { Label myLabel = new Label(); TextBox txtbox = new TextBox(); // Set the label's Text and ID properties. myLabel.ID = "LabelVol" + i.ToString(); myLabel.Text = "Volunteer " + i.ToString(); txtbox.ID = "TxtBoxVol" + i.ToString(); PlaceHolder1.Controls.Add(myLabel); PlaceHolder2.Controls.Add(txtbox); // Add a spacer in the form of an HTML
element. PlaceHolder2.Controls.Add(new LiteralControl("
")); PlaceHolder1.Controls.Add(new LiteralControl("
"));