Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Find() method return an array?

Tags:

c#

winforms

I want to locate a TextBox named "textBoxQH_N" where "_N" is a number from 1..96.

So, I've got this code:

String sTextBoxToFind = String.Format("textBoxQH{0}", QuarterHour);
TextBox tb = (TextBox)this.Controls.Find(sTextBoxToFind, true);

...but it gave me, "Cannot convert type 'System.Windows.Forms.Control[]' to 'System.Windows.Forms.TextBox'"

So I changed the second line to grab just the first returned val:

TextBox tb = (TextBox)this.Controls.Find(sTextBoxToFind, true)[0];

Which seems to work, but shouldn't a Control's Name property be unique to its owner? IOW, Find() should only return 0..1 controls, right?

like image 299
B. Clay Shannon-B. Crow Raven Avatar asked Mar 02 '26 01:03

B. Clay Shannon-B. Crow Raven


2 Answers

Find, with the second property set to true, is recursive. 'Name' is unique to that parent, but you're searching through lots of different parents. 'Name' isn't globally unique.

As suggested by Justin in another answer, First or FirstOrDefault is probably better than using [0] on the array. It does a better job of conveying your intentions to future readers.

like image 56
Servy Avatar answered Mar 03 '26 15:03

Servy


The Find method will find any matches, so even though it is only one match in your case, it could be numerous in other cases. You could probably use LINQ First here if you wanted something more semantically meaningful?

The MSDN on this is pretty clear on this method

like image 36
Justin Pihony Avatar answered Mar 03 '26 16:03

Justin Pihony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!