2013-08-02 29 views
2

我在想,如果有人可以幫助我提高我的代碼(?)C#代碼改進(數組列表)

三個星期前,我決定,這將是非常有用的學習C#/ C++(決定開始與我正在盡我所能,但我在理解一些基礎知識方面遇到了問題 - 例如數組。

我想通過點擊按鈕添加「x」文本框(其中「x」是numericUpDown的值)。

我發現了一個解決方案,如何做到這一點,但我有這種感覺,有可能以不同的(更好的)方式編寫(我認爲高級程序員會使用列表或數組)。

請原諒我,如果我錯了,正如我之前提到的 - 我是新的,並盡我所能學習。

這裏是我的代碼:

private void button1_Click(object sender, EventArgs e) 
{ 

    if (numericUpDown1.Value == 1) 
    { 
     txtbx1.AutoSize = true; 
     Controls.Add(txtbx1); 
     txtbx1.Location = new Point(70, 100); 
    } 
    else if (numericUpDown1.Value == 2) 
    { 
     txtbx1.AutoSize = true; 
     Controls.Add(txtbx1); 
     txtbx1.Location = new Point(70, 100); 

     txtbx2.AutoSize = true; 
     Controls.Add(txtbx2); 
     txtbx2.Location = new Point(70, 130); 
    } 
    else if (numericUpDown1.Value == 3) 
    { 
     txtbx1.AutoSize = true; 
     Controls.Add(txtbx1); 
     txtbx1.Location = new Point(70, 100); 

     txtbx2.AutoSize = true; 
     Controls.Add(txtbx2); 
     txtbx2.Location = new Point(70, 130); 

     txtx3.AutoSize = true; 
     Controls.Add(txtbx3); 
     txtbx3.Location = new Point(70, 160); 
    } 
} 
+9

這個問題會更加適合'代碼審查'http://codereview.stackexchange.com/ –

+0

看看'switch'語句 – Jonesopolis

+0

從StackOverflow「關於」頁面:「並非所有的問題都可以正常工作我們的格式,避免主要基於意見的問題,或者可能產生討論而不是回答的問題。「這種格式的問題非常主觀。它本身沒有任何問題,如果它更復雜,那麼對於如何完成你正在嘗試做的事情會有更多的意見*。這就是爲什麼@ Chips_100建議去不同的網站。我其實不知道codereview.stackeschange.com!我很高興剛剛瞭解它。只是未來的預測。 –

回答

6

不要重複自己,在一個簡單的你可以這樣做:

private void button1_Click(object sender, EventArgs e) 
{ 

    int y = 100; 
    int x = 70; 
    for (int i = 0; i < numericUpDown1.Value; i++) 
    { 
     var txtbx = new TextBox(); 
     txtbx.AutoSize = true; 
     Controls.Add(txtbx); 
     txtbx.Location = new Point(x, y); 

     // Increase the y-position for next textbox. 
     y += 30; 
    } 
} 
5

而不是預創建TextBox控制,你總是可以動態創建它們:

// This is optional - in case you want to save these for use later. 
List<TextBox> newTextBoxes = new List<TextBox>(); 

private void button1_Click(object sender, EventArgs e) 
{ 
    int y = 100; 
    for (int i=0;i<numericUpDown1.Value;++i) 
    { 
     TextBox newBox = new TextBox 
     { 
      AutoSize = true, 
      Location = new Point(70, y) 
     }; 
     y += 30; 
     Controls.Add(newBox); 

     // This saves these for later, if required 
     newTextBoxes.Add(newBox); 
    } 
} 
0

你可以做兩件事之一。首先是使用switch聲明,或者我的首選是使用循環,但使用gui時可能會有點棘手。事情是這樣的:

for (int i = 0; i < numericUpDown1.Value; i++) 
    { 
     //Make an TextBox Array or instantiate a new TextBox each iteration 
      //and set properties here 
    } 

但正如我所說,這些文本框的放置可能會變得有些棘手,如果你在一個循環做到這一點,所以它會更容易只使用switch聲明。它們相對簡單易用,但如果遇到任何問題,請告知我們。

此外,您的代碼註釋,給文本框和其他GUI元素有意義的名稱;我知道設計師會自動分配他們的名字,現在這不是問題,但是在處理很多元素時會變得非常混亂。