I’m trying to get a TextBox control from a collection which only contains TextBoxes as follow:
IEnumerable<TextBox> tbx = this.grd.Children.OfType<TextBox>();
And then I’m trying to get the TextBox control that has the name “tbxLink” as follow:
TextBox txtBox = (TextBox)tbx.Select(x => x.Name == "tbxLink");
But it gives me this error message at runtime:
Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Windows.Controls.TextBox,System.Boolean]' to type 'System.Windows.Controls.TextBox'.
What am I missing here?
Edit:
Some more tries with some more error messages:
Using .Where:
Unable to cast object of type 'WhereEnumerableIterator`1[System.Windows.Controls.TextBox]' to type 'System.Windows.Controls.TextBox'.
Using .Single:
Sequence contains no matching element
Using .First :
Sequence contains no matching element
Using FirstOrDefault or SingleOrDefault makes the tbx variable null
You would normally use Where like this:
where textBoxes is
IEnumerable<TextBox>.But if you know there is only one text box with that name you need
which will return null (of more precisely
default(TextBox)) if there is no text box of that name,or alternatively
which throws an exception if no text box of that name exists.
If there are multiple text boxes with the same name you may want to use
or
As an example running this code in LINQPad works as expected:
I have duplicated this using WPF, e.g.