Reputation: 13
I want the following code to give me the exact number of S values from the textboxes named : Box1_1 , Box1_2 , Box1_3, Box1_4, Box1_5 ...
But when i try to see the value it's always blank. What can i do ?
for (int i = 1; i <= 7; i++){
for (int j = 1; j <= 10; j++){
string box = "Box" + i.ToString() + "_" + j.ToString();
TextBox nameBox = new TextBox();
nameBox.Name = box;
if(string.Compare(nameBox.Text, "S")==0){
numberS++;
}
}
}
Upvotes: 1
Views: 107
Reputation: 16711
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();
TextBox
controls using OfType<TextBox>()
"Box"
. The corresponding Linq is Where(t => t.Name.StartsWith("Box"))
. "S"
. The corresponding linq is Where(t => t.Text.StartsWith("S"))
. I have combined these in a single Where
..Count()
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
.
Upvotes: 1
Reputation: 1
First of all, you need a collection of your TextBox'es or scrap them from your window. Example of how to do the second is here.
Here is your code that I modified:
public int CountS()
{
var numberS = 0;
for (int i = 1; i <= 7; i++)
{
for (int j = 1; j <= 10; j++)
{
string box = "Box" + i.ToString() + "_" + j.ToString();
TextBox nameBox
= UIHelper.FindChild<TextBox>(Application.Current.MainWindow, box); //using example linked above
//= textBoxes.First(tbx => tbx.Name == box); //if you got collection of your textboxes
numberS += nameBox.Text.Count(c => c == 'S'); //if you wont also count a small "s" add .ToUpper() before .Count
}
}
return numberS;
}
Upvotes: 0