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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With