2011-02-15 72 views
0

我想創建基於數組的標籤,但我總是隻能獲得一個標籤。C#從數組創建標籤

private void button1_Click(object sender, EventArgs e) 
    { 
     Debug.WriteLine(hardrive.GetHardDriveName.Count); 
     Label[] lblHDDName = new Label[hardrive.GetHardDriveName.Count]; 

     for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
     { 
      int x = 10; 
      int y = 10; 

      lblHDDName[i] = new Label(); 
      lblHDDName[i].Location = new System.Drawing.Point(x, y); 
      lblHDDName[i].Text = "Test"; 
      groupBoxHDD.Controls.Add(lblHDDName[i]); 

      y += 10; 
     } 
    } 

調試

Debug.WriteLine(hardrive.GetHardDriveName.Count); 

顯示陣列中的兩個項目。

問題是在GroupBox中只有一個標籤而不是兩個。

回答

5

y變量在for循環,而不是外部定義。因此,對於循環的每次執行,您將其初始化爲10並在您的System.Drawing.Point中使用它。如果要跟蹤在循環結束時完成的增量,則必須在for循環之前聲明並初始化y

int y = 10; 
for (int i = 0; i < ...; i++) 
{ 
    // use y 
    ... 

    // increment it 
    y += 10; 
} 
+0

好的,謝謝,多麼愚蠢的錯誤 – Chuck 2011-02-15 13:42:24

1

您在循環的每次迭代開始時將y重置爲10。

將x和y的聲明移到循環外部。

這樣的:

for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
{ 
    int x = 10; 
    int y = 10; 
    .... 

應該是:

int x = 10; 
int y = 10; 
for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
{  
    .... 
1

不,你創建了所有正確的標籤 - 但他們都得到了(10,10)相同的位置。如果你想看到他們的不止一個,你需要把他們在差異的地方:)要麼宣佈y外循環,或簡單地使用:

lblHDDName[i].Location = new Point(10, i * 10 + 10); 

而不是硬編碼的位置,你可能想要查看某些描述的自動排列控件。

此外,它看起來像你根本不需要標籤數組 - 你以後不使用它們。例如,你可以有:

private void button1_Click(object sender, EventArgs e) 
{ 
    for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
    { 
     // Assuming you're using C# 3 or higher 
     Label label = new Label { 
      Location = new Point(10, i * 10 + 1), 
      Text = "test" 
     }; 
     groupBoxHDD.Controls.Add(label); 
    } 
} 

甚至:

private void button1_Click(object sender, EventArgs e) 
{ 
    for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
    { 
     groupBoxHDD.Controls.Add(new Label { 
      Location = new Point(10, i * 10 + 1), 
      Text = "test" 
     }); 
    } 
} 
1

移動

int x = 10; 
int y = 10; 

出來的for循環

1

一個你的問題是,xy聲明是內循環,從而y永遠是即使你在循環結尾添加10。標籤將始終處於相同的位置。在for循環之外修復int y = 10這一舉動。你應該在那裏移動int x = 10

0

移動

int x=10; 
int y=10; 

循環

和增量ÿ30

外,如果(你想要的標籤,自身對準他們的出發點

int x=10; 

可以保持環內

int x = 10; 
for (int i = 0; i < hardrive.GetHardDriveName.Count; i++) 
    { 

     int y = 10; 

     lblHDDName[i] = new Label(); 
     lblHDDName[i].Location = new System.Drawing.Point(x, y); 
     lblHDDName[i].Text = "Test"; 
     groupBoxHDD.Controls.Add(lblHDDName[i]); 

     y += 30; 
    }