如何检查(c#)ControlCollection.Find()是否返回了结果

时间:2011-04-12 11:32:15

标签: c# winforms

我在C#中使用ControlCollection.Find()方法来查找表单中的一些图片框。

我将返回的结果存储在Control []数组中。如何判断Find()是否成功???

代码

Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
    UpdateRes = update_status(TagNo, Status);

其中TagNo是一个包含Control的确切名称的字符串。

是。我正在使用控件的确切名称。我之前已经成功使用了Find()方法(当Control确实出现在Collection中时)。我这次遇到了问题,因为收藏中可能存在或可能不存在控件。

3 个答案:

答案 0 :(得分:6)

你试过吗?

var result = controlCollection.Find(contolName,true);
if(result == null || result.Length == 0)
{
   // fail to find
}

您可以使用此方法查看所有控件的列表

    public void FillControls(List<string> container,Control control)
    {
        foreach (Control child in control.Controls)
        {
            container.Add(child.Name);
            FillControls(container,child);
        }
    }

然后使用:

    public Form1()
    {
        InitializeComponent();

        List<string> controls = new List<string>();
        FillControls(controls,this);
    }

答案 1 :(得分:0)

最安全的方法是检查返回的数组是否不是null并且长度大于0:

Control[] children = this.Find("mypic", true);
if (children != null && children.Length > 0)
{
   //OK to proceed...
}

答案 2 :(得分:0)

如果没有找到控件,

Find()方法将返回一个空数组(从不为null)。所以你应该简单地做一些事情:

Control[] controls = myForm.Find("picbox", true);
if (controls.Length > 0) {
   // Do logic when picture boxes are found
} else {
   // Do logic when there are no picture boxes
}