2013-06-05 40 views
1

我想寫一個程序,它將創建一個新的TextBox,一旦Button3被點擊。 由於某些原因,C#不能識別txtRun。它表示名稱txtRun在當前上下文中不存在。這裏是我的代碼:單擊按鈕後如何創建新的文本框?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      textBox1.Text += "a"; 
     } 

     private void button2_Click(object sender, EventArgs e) 
     { 
      textBox1.Text += "b"; 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 

     private void button3_Click(object sender, EventArgs e) 
     { 

      txtRun = new TextBox(); 
      txtRun.Name = "txtDynamic"; 
      txtRun.Location = new System.Drawing.Point(20, 18); 
      txtRun.Size = new System.Drawing.Size(200, 25); 
      // Add the textbox control to the form's control collection   
       this.Controls.Add(txtRun); 
     } 

     } 



     } 
    } 
} 
+0

您還需要給每個新的TextBox一個不同的**位置()**,否則每次單擊button3時新的TextBox就會坐在上一個(s)頂部,並且最終會出現一個大疊加。 –

+0

我建議使用諸如FlowLayoutPanel或TableLayoutPanel之類的東西來分配一個不同的位置,因爲它可能變得非常麻煩並且浪費時間,特別是如果你只是想要格式化的網格。 – CodeCamper

回答

3

你需要在使用它之前在C#中聲明一個變量。

二者必選其一

TextBox txtRun = new TextBox(); 

,或者使用implicitly typed變量:

var txtRun = new TextBox(); 
2

也許這個問題是你不聲明類型

var txtRun = new TextBox(); 
0

除了給出尋找答案在你提供的代碼剪輯中,看起來你有太多的大括號。更具體地說,最後兩個 - 你不需要那些。

0

問:

出於某種原因,C#不承認txtRun。它表示名稱txtRun在當前上下文中不存在。

答:

在你的聲明

txtRun = new TextBox(); 

您已經創建了一個變量txtRun但沒有給它一個類型。就像當你創建一個字符串或int文本框也不例外,你必須使用類文本框的名稱txtRun之前這樣

TextBox txtRun = new TextBox(); 

你也可以使用var字代替文本框,讓編譯器猜測你。

這將解決您的直接問題。

但是,這裏真正的問題是,如果用戶要無限次地點擊按鈕,您正在創建無限數量的文本框。另外你可能沒有意識到它,但第二次按下按鈕時,它將TextBox放在原件下面,所以你可能沒有意識到它,因爲你輸入的文本將保留,但我向你保證你正在創建一堆TextBoxes,它是不好。我不確定你正在完成什麼取決於你的情況,你可以通過幾種不同的方式來解決這個問題。

方案1(你只想要1動態創建文本框)

創建一個變量來檢查,如果文本框已經被創建的,因此纔有一個。 *注意你應該真的創建或調用你的點擊方法以外的TextBox,因爲你會失去它的範圍。

方案2(您想創建動態超過1個文本框)

創建一個文本框列表或數組所以很容易追蹤您的動態創建文本框 使用的東西,如FlowLayoutPanel的或TableLayoutPanel中來處理放置你的文本框,特別是如果你想使它們像網格一樣,或者確保某個位置對於每個新的TextBox都是唯一的。 *請注意,您仍然應該以某種方式真正創建或調用您的點擊方法外的TextBox,因爲您將失去它的範圍。

如果你需要,請告訴我,我會進入任何情況下的更多細節。

0

嘗試

var txtRun = new TextBox(); 
    txtRun.Name = "txtDynamicTemp"; 
    txtRun.Location = new System.Drawing.Point(20, 18); 
    txtRun.Size = new System.Drawing.Size(200, 25); 
    // Add the textbox control to the form's control collection   
     this.Controls.Add(txtRun) 

;

相關問題