[英]Input from C# Dynamically Created Text Boxes
我正在使用在其中一种解决方案中找到的代码来在程序运行时在表单上动态生成标签和文本框。 生成标签和盒子的代码可以正常工作。 我的问题是,我将需要能够对用户输入到动态创建的那些文本框中的内容进行处理,但是我不确定如何访问用户输入以将其定义为变量。 谢谢您的帮助。
我使用的代码如下:
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);
}
首先,您需要给控件指定一些名称,以便轻松访问它们。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.