This is a cheeky little one-liner using Linq
(split over multiple lines for clarity):
var textBoxes = this.Controls
.OfType<TextBox>() // controls that are TexteBoxes
.Where(t => t.Name.StartsWith("Box") && t.Text.StartsWith("S"))
.ToList();
int numberS = textBoxes.Count();
- We get all
TextBox
controls using OfType<TextBox>()
- This assumes the name of the TextBoxes you're interested in start with
"Box"
. The corresponding Linq is Where(t => t.Name.StartsWith("Box"))
.
- It looks like you're only interested in the TextBoxes that have a value that starts with
"S"
. The corresponding linq is Where(t => t.Text.StartsWith("S"))
. I have combined these in a single Where
.
- Then we get the count:
.Count()
- If you want the count of textboxes that contain
S
(not just start with S
) then use t.Text.Contains("S")
in the Where
clause instead.
If you want to get the TextBox
names (Box1_1
, Box1_2
, etc) then you can use Select
which will take the Name
property from each TextBox
and return a List<string>
var txtNames = this.Controls
.OfType<TextBox>() // controls that are TexteBoxes
.Where(t => t.Name.StartsWith("Box") && t.Text.StartsWith("S"))
.Select(t => t.Name) // select textbox names
.ToList();
txtNames
is a List<string>
containing the textbox names which start with S
.