如何查找 Windows 窗体面板中是否存在标签

Awa*_*eem 2 c# if-statement visual-studio winforms

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");
        }
Run Code Online (Sandbox Code Playgroud)

意思是说如果标签不存在,我的其他部分就不起作用。

C4d*_*C4d 5

只需像这样循环容器:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以跳过类型检查部分并直接输入名称:

foreach(Control ctrl in panel1.Controls)
{
    if(ctrl.Name == "label1")
    {
        // check ctrl.Name
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这只是循环直接控制。如果里面有一个容器,panel1你将无法控制它。

  • 另请注意,您需要知道“Label”的“Name”。如果您在代码中创建了它,则还必须设置“Name”属性才能使其正常工作。顺便说一句:这个 __property__ 只是一个 __string__ 并且不能保证是唯一的甚至是设置的!不要与变量的 __name__ 混淆,即使默认情况下它们是相同的..!! (2认同)