2013-04-27 34 views
2
for (int f = 1; f <= 6; f++) 
{ 
    textBox{f+11} = (loto[f].ToString()); 
} 

嗨, 我想學習我自己的c#。對不起,這noobish問題:)如何在變量名上使用變量?

更spesific,這就是我想要的東西:

的快捷方式編寫代碼那樣:

textBox12.Text = loto[1].ToString(); 
textBox11.Text = loto[2].ToString(); 
textBox10.Text = loto[3].ToString(); 
textBox9.Text = loto[4].ToString(); 
textBox8.Text = loto[5].ToString(); 
textBox7.Text = loto[6].ToString(); 

此代碼工作,但我想它寫在for循環中

+0

什麼是loto?顯示所有相關的代碼。什麼確切的錯誤? – 2013-04-27 08:23:27

+0

我編輯了我的問題,謝謝你的幫助 – 1342 2013-04-27 08:28:55

回答

1

你可以使用一個List<TextBox>並在構造函數初始化,該呼叫後InitialiseComponent()你將在構造函數中看到。

方法如下:

首先添加到您的窗體類List<TextBox>如下:

private List<TextBox> textboxes = new List<TextBox>(); 

然後在你的構造是這樣的(改變Form1到窗體的構造函數的名稱)初始化列表:

public Form1() 
{ 
    // ... 

    InitializeComponent(); 

    // ... 

    textboxes.Add(textBox1); 
    textboxes.Add(textBox2); 
    textboxes.Add(textBox3); 
    // ...etc up to however many text boxes you have. 
} 

然後,當你要訪問的文本框,你可以這樣做是這樣的:

for (int f = 1; f <= 6; ++f) 
{ 
    textboxes[f+11].Text = loto[f].ToString(); // From your example. 
} 
+0

你做了我的一天兄弟,謝謝。我不能upvote,但只要我什麼時候我可以upvote它 – 1342 2013-04-27 09:00:11

3

您可以使用字典。

Dictionary<int, TextBox> dictionary = new Dictionary<int, TextBox>(); 

dictionary.Add(1, textbox1); 
... // add the other textboxes 


// access the dictionary via index 
dictionary[f+11] = ... 
0

你不行。您必須將它們存儲在字典列表中並以這種方式訪問​​它們。所以

  • 控件添加到列表/字典
  • 在for循環,通過索引來訪問他們
1

我不確定您的TextBox控件是否已經在窗體上。如果不是,並且想要動態創建TextBox控件,則可以這樣做:

for (int f = 1; f <= 6; f++) 
{ 
    Dictionary<int, TextBox> dict = new Dictionary<int, TextBox>(); 
    dict.Add(f, new TextBox()); 
    dict[f].Location = new Point(0, f * 20); 
    dict[f].Text = loto[f].ToString(); 
    this.Controls.Add(dict[f]); 
} 
+0

我想這對我來說太高了。 我在C#上的水平是; 我創建了Hello World窗口並創建了我的第一個應用程序:[link] http://yadi.sk/d/c3kN8S7o4O88K – 1342 2013-04-27 09:07:58