2012-09-08 36 views
2

我在運行時創建了一個標籤數組。現在我有一個問題來從其他功能訪問這些標籤。如何訪問動態創建的標籤陣列

動態創建:

private void Form1_Shown(object sender, EventArgs e) 
{ 
    Label[] Calendar_Weekday_Day = new Label[7]; 
    for (int i = 0; i < 7; i++) 
    { 
     Calendar_Weekday_Day[i] = new Label(); 
     Calendar_Weekday_Day[i].Location = 
            new System.Drawing.Point(27 + (i * 137), 60); 
     Calendar_Weekday_Day[i].Size = new System.Drawing.Size(132, 14); 
     Calendar_Weekday_Day[i].Text = "Montag, 01.01.1970"; 
     this.TabControl1.Controls.Add(Calendar_Weekday_Day[i]); 
    } 
} 

和作用,我想訪問標籤的動態創建的數組:顯示

private void display_weather_from_db(DateTime Weather_Startdate) 
{ 
    Calendar_Weekday_Day[0].Text = "Test1"; 
    Calendar_Weekday_Day[1].Text = "Test2"; 
} 

錯誤:

名稱「Calendar_Weekday_Day '目前不存在 上下文Form1.cs 1523 25 Test

我tryed這一點,但並沒有幫助:(

public partial class Form1 : Form 
{ 
    private Label[] Calendar_Weekday_Day; 
} 

有人的想法?

回答

3

我猜你需要的只是

Calendar_Weekday_Day = new Label[7]; 

代替

Label[] Calendar_Weekday_Day = new Label[7]; 

Form_Shown。正如現在寫的,您將該列表存儲在本地變量中而不是實例字段中。

+0

是!這工作! Thx:D –

+0

@Markus:不客氣:) – Vlad

+0

想知道是否有任何推理背後的投票... – Vlad

0

問題很可能是範圍或初始化不足。 Calendar_Weekday_Day只存在於Form1_Shown上下文中。如果你嘗試從另一種方法訪問它,你將無法看到它(當它是私有的時候,它還沒有被初始化爲添加新的元素會有問題)。你有兩個選擇:

  • 變化範圍(使Calendar_Weekday_Day在窗體類的私人財產,不要忘了初始化)
  • 搜索控制通過訪問this.TabControl1.Controls

你使用private IEnumerable<Label> Calendar_WeekendDay或甚至IList<Label>也可能會更好,從而爲您稍後訪問控件提供更多的靈活性。

0

刪除重複宣告

private void Form1_Shown(object sender, EventArgs e) 
{ 
    Calendar_Weekday_Day = new Label[7]; // removed Label[] 

...剩下的就是同

這將是所需的最小的變化,但你應該注意編譯器警告。它最有可能警告你,你重新宣佈領域。

0

如果您的tabcontrol只包含標籤,這樣

private void display_weather_from_db(DateTime Weather_Startdate) 
{ 
Label[] Calendar_Weekday_Day = this.TabControl1.Controls.OfType<Label>().ToArray(); 

Calendar_Weekday_Day[0].Text = "Test1"; 
Calendar_Weekday_Day[1].Text = "Test2"; 

} 

如果你有更多的篩選其他標籤,所以首先

for ..... 
    ... _Day[i].Size = new System.Drawing.Size(132, 14); 
    Calendar_Weekday_Day[i].Text = "Montag, 01.01.1970"; 
    Calendar_Weekday_Day[i].Tag= "Weather";// specify your label tag 
    this.TabControl1.Controls.Add(Calendar_Weekday_Day[i]); 
    .... 

然後

private void display_weather_from_db(DateTime Weather_Startdate) 
{ 
Label[] Calendar_Weekday_Day = this.TabControl1.Controls.OfType<Label>().Where(X=>X.Tag!=null && X.Tag=="Weather").ToArray(); 


Calendar_Weekday_Day[0].Text = "Test1"; 
Calendar_Weekday_Day[1].Text = "Test2"; 

}