我正在使用我在其中一个解决方案中找到的代码,在程序运行时动态生成表单上的标签和文本框。生成标签和框的代码工作正常。我的问题是,我需要能够将用户的输入做一些动态创建的文本框,但我不确定如何访问用户的输入以便定义它作为一个变量。谢谢您的帮助。
我使用的代码如下:
private void button2_Click(object sender, EventArgs e)
{
int intGroups = Convert.ToInt32(maskedTextBox1.Text);
int n = intGroups;
for (int i = 1; i <= n; i++)
{
//Retrieved from http://stackoverflow.com/questions/15008871/how-to-create-many-labels-and-textboxes-dynamically-depending-on-the-value-of-an
//Create label
Label portTypeLabel = new Label();
portTypeLabel.Text = String.Format("Port Type (FastEthernet/GigabitEthernet) {0}", i);
Label portGroupLabel = new Label();
portTypeLabel.Text = String.Format("Port Group (the first number before the slash, usually 1) {0}", i);
Label startIntNumLabel = new Label();
portTypeLabel.Text = String.Format("Group {0} starting interface number", i);
//Position label on screen
portTypeLabel.Left = 10;
portTypeLabel.Top = (i) * 20;
/* Must add the rest of the code for displaying the labels here
*/
//Create textbox
TextBox textBox = new TextBox();
ComboBox combo = new ComboBox();
//Position textbox on screen
textBox.Left = 120;
textBox.Top = (i) * 20;
combo.Left = 120;
combo.Top = (i) * 20;
//Add controls to form
this.Controls.Add(portTypeLabel);
this.Controls.Add(textBox);
this.Controls.Add(combo);
}
答案 0 :(得分:1)
首先,您需要为控件提供一些名称以便轻松访问它们。
TextBox textBox = new TextBox();
textBox.Name = "textbox" + i.ToString();
其次,如果您需要创建选择方法,则需要定义事件
textBox.TextChanged += new System.EventHandler(this.TextChanged);
在这种方法中你可以把switch..case用文本框来检查事件(也许用最后的数字)。
void TextChanged(object sender, EventArgs e){
TextBox t = (TextBox)sender;
// t is the textbox you referred
MessageBox.Show(t.Name);
}