我如何通过它的名称从 texboxes 中获取值

How can i take the values from texboxes by the name of it

我想要以下代码从名为 Box1_1 , Box1_2 , Box1_3, Box1_4, Box1_5 ...

但是当我尝试查看值时,它总是空白。我能做什么?

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++;
        }
    }
}

首先,您需要收集 TextBox 或从 window 中删除它们。如何执行第二个示例是 here

这是我修改过的代码:

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;
        }

这是一个使用 Linq 的厚脸皮的小单行(为清楚起见分成多行):

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();          
  • 我们使用 OfType<TextBox>()
  • 获得所有 TextBox 控件
  • 这假定您感兴趣的文本框的名称以 "Box" 开头。对应的Linq为Where(t => t.Name.StartsWith("Box"))
  • 您似乎只对值以 "S" 开头的文本框感兴趣。对应的linq是Where(t => t.Text.StartsWith("S"))。我将这些组合成一个 Where.
  • 然后我们得到计数:.Count()
  • 如果您想要计算包含 S 的文本框的数量(不只是以 S 开头),那么请在 Where 子句中使用 t.Text.Contains("S")

如果您想获取 TextBox 名称(Box1_1Box1_2 等),那么您可以使用 Select,它将获取 Name 属性 来自每个 TextBox 和 return 一个 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 是一个 List<string> 包含以 S.

开头的文本框名称