Why does the Find () method return an array?

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

So, I have this code:

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

... but he gave me: "It is not possible to convert the type" System.Windows.Forms.Control [] "to" System.Windows.Forms.TextBox "

So, I changed the second line to capture only the first val returned:

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

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

+3
source share
4 answers

Find, , true, . "" , . "" .

, First FirstOrDefault, , , [0] . .

+7

Find , , , . LINQ First , - ?

MSDN

+3

. :

Control[] tb = this.Controls.Find("textBox1", true); //change the name of the control

TextBox[] tbs = (TextBox[])this.Controls.Find("tb1", true);

, CAST ( TextBoxes). , ,

+1
source

From an API design point of view, formats 0 and 1 are best returned as IEnumerable / collection / array to avoid null checking.

As indicated in other answers, the name of the control does not have to be globally unique, and Find can indeed return more than one element.

MSDN Link - Controls.Find

+1
source

All Articles