你好我正在當我點擊添加按鈕話反而會使得使用該代碼的2個新的文本框有2個文本框和2個按鈕 的程序:C#獲取文本
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;
}
你可以遍歷'this.Controls'中的所有項目來找到你想要的名字。或者有一個單獨的'Dictionary',您可以在其中保留對新創建的文本框的引用以方便訪問。 –
Corak