C#从运行时创建的文本框中获取文本

您好我正在制作一个包含2个文本框和2个按钮的程序当我按下添加按钮时,它将使用此代码创建2个新文本框:

private void ADD_ROW_Click(object sender, EventArgs e) { //Make the NEW_TEXTBOX_1 HOW_FAR += 1; TextBox NEW_TEXTBOX_1 = new TextBox(); NEW_TEXTBOX_1.Name = "NAME_TEXTBOX_" + HOW_FAR.ToString(); //Set NEW_TEXTBOX_1 font NEW_TEXTBOX_1.Font = new Font("Segoe Print", 9); NEW_TEXTBOX_1.Font = new Font(NEW_TEXTBOX_1.Font, FontStyle.Bold); //Set pos and size and then create it. NEW_TEXTBOX_1.Location = new System.Drawing.Point(16, 71 + (35 * HOW_FAR)); NEW_TEXTBOX_1.Size = new System.Drawing.Size(178, 29); this.Controls.Add(NEW_TEXTBOX_1); //Make the PRICE_TEXTBOX_ TextBox NEW_TEXTBOX_2 = new TextBox(); NEW_TEXTBOX_2.Name = "PRICE_TEXTBOX_" + HOW_FAR.ToString(); //Set NEW_TEXTBOX font NEW_TEXTBOX_2.Font = new Font("Segoe Print", 9); NEW_TEXTBOX_2.Font = new Font(NEW_TEXTBOX_2.Font, FontStyle.Bold); //Set pos and size and then create it. NEW_TEXTBOX_2.Location = new System.Drawing.Point(200, 71 + (35 * HOW_FAR)); NEW_TEXTBOX_2.Size = new System.Drawing.Size(89, 29); this.Controls.Add(NEW_TEXTBOX_2); //Change pos of the add button ADD_ROW.Location = new System.Drawing.Point(295, 71 + (35 * HOW_FAR)); this.Height = 349 + (35 * HOW_FAR); this.Width = 352; } 

这非常有效,但现在我想从新制作的文本框中获取文本,我该怎么做?

这不起作用,因为它说:NAME_TEXTBOX_1在当前上下文中不存在。

  private void button2_Click(object sender, EventArgs e) { string tmpStr = NAME_TEXTBOX_1.Text; } 

您需要将变量声明移到ADD_ROW_Click事件处理程序之外,以便可以在该块之外访问它;

 TextBox NEW_TEXTBOX_1; private void ADD_ROW_Click(object sender, EventArgs e) { //Make the NEW_TEXTBOX_1 HOW_FAR += 1; NEW_TEXTBOX_1 = new TextBox(); //remove "TextBox" since we declared it above NEW_TEXTBOX_1.Name = "NAME_TEXTBOX_" + HOW_FAR.ToString(); //... 

替代方案,可能更好,取决于文本框的数量,是将您创建的每个TextBox添加到List中。 然后,您可以从中迭代该List并找到所需的TextBox。 例如

 List allTextBoxes = new List(); private void ADD_ROW_Click(object sender, EventArgs e) { //Make the NEW_TEXTBOX_1 HOW_FAR += 1; TextBox NEW_TEXTBOX_1 = new TextBox(); //...fill out the properties //add an identifier NEW_TEXTBOX_1.Tag = 1; allTextBoxes.Add(NEW_TEXTBOX_1); } 

然后当你想要一个特定的TextBox

 private void button2_Click(object sender, EventArgs e) { TextBox textBox1 = allTextBoxes.Where(x => x.Tag == 1).FirstOrDefault(); string tmpStr = ""; if(textBox1 != null) tmpStr = textBox1.Text; } 

或者,特别是如果您将要有很多TextBox,您可以将它们存储在Corak中,如Corak在评论中所建议的那样。

您在ADD_ROW_Click方法中声明了NAME_TEXTBOX_1,这就是它在button2_Cick方法中不可用的原因。

您可以在类级别声明文本框以在两个位置访问它。

(你应该重新命名你的变量 – 例如TextBoxPrice)

一个简单的解决方案:例如,创建一个名为“NEW_TB”的私有字段。 在你的button2_Click(..){string tmpStr = NEW_TB.Text; 添加你的ADD_ROW_Click(..)方法NEW_TB = NAME_TEXTBOX_1;

如果我理解你的问题,这应该有效。

全局化您的textboxes

 TextBox NEW_TEXTBOX_1; 

然后在你的方法中启动它们:

 NEW_TEXTBOX_1 = new TextBox(); 

OMG别介意抱歉,我找到了一个好方法:D

  var text = (TextBox)this.Controls.Find("PRICE_TEXTBOX_1", true)[0]; text.Text = "PRO!"; 

这很好用:)