how to check if (c#) ControlCollection.Find() has returned a result
I am using ControlCollection.Find() method in C# to find some picture boxes present in my form.
I am storing the returned result in a Control[] array. How do I find out if the Find() was successful or not???
Code
Control[] temp = pictureBoxCollection.Find(TagNo, true);
if(temp.Length>0)
UpdateRes = update_status(TagNo, Status);
where TagNo is a string c开发者_StackOverflow中文版ontaining the Control's exact name.
Yes. I'm using the control's exact name. And I have used the Find() method successfully earlier (when the Control was surely present in the Collection). I am having a problem this time because the control may or may not be present in the Collection.
Have you tried?
var result = controlCollection.Find(contolName,true);
if(result == null || result.Length == 0)
{
// fail to find
}
You can use this method to see list of all controls
public void FillControls(List<string> container,Control control)
{
foreach (Control child in control.Controls)
{
container.Add(child.Name);
FillControls(container,child);
}
}
And then use:
public Form1()
{
InitializeComponent();
List<string> controls = new List<string>();
FillControls(controls,this);
}
Safest way will be to check if the returned array is not null
and has Length of more than 0:
Control[] children = this.Find("mypic", true);
if (children != null && children.Length > 0)
{
//OK to proceed...
}
Find() method will return an empty array (never null) if no controls were found. So you should simply do something like:
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
}
精彩评论