2016-04-30 11 views
1
if (panel1.Contains(label1)) // if label1 is exist it shows label is exist if label2 is not exist then mean else part... how to identify it is not exist. 
     { 
      MessageBox.Show("Label 1 is Exist"); 
     } 

意思是說我的其他部分不工作,如果標籤不存在。如何查找標籤是否存在或不在Windows窗體面板

+0

使用查找控件將會找到你想要的 –

+0

你可以通過一個例子來解釋嗎 –

回答

3

就循環這樣的容器:

foreach(Control ctrl in panel1.Controls) 
{ 
    // Check if control is of type label 
    if(ctrl.GetType() == typeof(Label)) 
    { 
     // check the name of the label 
     if(ctrl.Name == "label1") 
     { 
      // do what ever you want 
      MessageBox.Show("Label 1 existing"); 
     } 
    } 
} 

你也可以跳過類型檢查部和直去的名字:

foreach(Control ctrl in panel1.Controls) 
{ 
    if(ctrl.Name == "label1") 
    { 
     // check ctrl.Name 
    } 
} 

注:這只是循環直接控制。如果panel1裏面有一個容器,你就不會得到它的控制。

+2

另外請注意,你需要知道'Label'的'Name'。如果你已經在代碼中創建了它,你還必須設置'Name'屬性來使其工作。順便說一句:這__property__只是一個__string__,並不保證是唯一的,甚至設置!不要與變量__name混淆,儘管默認情況下它們是相同的。 – TaW

+1

非常感謝。你解決了我的問題。 –

相關問題