2015-04-29 42 views
0

我想添加一個字符串的列表,用作Windows窗體上標籤的文本組件。下面是我用來做這個的代碼。我有它生成一個消息框來顯示我正在創建什麼,但是當我將它們添加到窗體時,儘管每個字符串彈出消息框指示列表正確填充,但窗體上只顯示第一個字符串。任何幫助都會很棒。動態添加組件到Windows窗體C#

List<Label> labelList; 

    public void ShowDialog(List<String> columns) 
    { 
     labelList = new List<Label>(); 
     Form updateDialog = new Form(); 
     updateDialog.Width = 500; 
     updateDialog.Height = 500; 


     for (int i = 0; i < columns.Count(); i++) 
     { 
      //Label label = new Label() {Text=columns[i].ToString() }; 

      labelList.Add(new Label() {Text=columns[i].ToString()}); 
     } 

     for (int j = 0; j < labelList.Count(); j++) 
     { 

      updateDialog.Controls.Add(labelList[j]); 
      MessageBox.Show(labelList[j].Text.ToString()); 
     } 
+0

因爲你把他們都在彼此的頂部。你需要設置'Location'屬性(或'Top' /'Left')來將它們放在你可以看到它們的地方。 –

回答

1

您需要設置創建的標籤的位置。它們在位置(0,0)上彼此重疊。

+0

嘿,這很有道理,對不起第一次在C#中工作。我的背景都是在java中,所以我認爲它會有一些基本的默認佈局管理器,並將它們從左到右放置。我將採取這一點,並找出如何動態調整位置。謝謝! – user519670

0

正在將控件添加到form,但它們對您不可見。只需爲每個Label設置不同的位置,您就會看到它們。

您還可以精確的代碼使用1個循環,而不是:

int yAxis = 10; 
for (int i = 0; i < columns.Count(); i++) 
{ 
    //create label 
    Label newLbl = new Label() {Text=columns[i].ToString()}; 
    newLbl.Location = new Point(10, yAxis * i); //will create a column of all labels, you can use your oown logic too 

    //add to list 
    labelList.Add(newLbl); 

    //add to form 
    updateDialog.Controls.Add(newLbl); 

    //show on msg box 
    MessageBox.Show(newLbl.Text.ToString()); 
} 
+0

這是真的我可以,我想我會的。感謝您的建議! – user519670

相關問題