从多个 TextBox 元素获取值 [英] Get value from multiple TextBox elements

查看:26
本文介绍了从多个 TextBox 元素获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个不同的 TextBox 元素,命名为e0"、e1"、e2"、e3".我知道有多少,我只想能够遍历它们并获取它们的值,而不是手动输入每个值.

I have a few different TextBox elements named as followed "e0", "e1", "e2", "e3". I know how many there are and I just want to be able to loop through them and grab their values rather than typing each one out manually.

我假设我会做这样的事情,我只是不知道如何访问该元素.

I'm assuming I'll be doing something like this, I just don't know how to access the element.

for(int i= 0; i < 4; ++i) {
    string name = "e" + i;
    // How do I use my newly formed textbox name to access the textbox 
    // element in winforms?
}

推荐答案

我建议不要使用这种方法,因为它容易出错.如果您想重命名它们,如果您忘记这一点并添加名称为 e... 的其他控件怎么办?

I would advise against this approach since it's prone to errors. What if you want to rename them, what if you'll forget about this and add other controls with name e...?

相反,我会将它们收集在一个容器控件中,例如 面板.然后就可以使用LINQ找到相关的TextBoxes:

Instead i would collect them in a container control like Panel. Then you can use LINQ to find the relevant TextBoxes:

var myTextBoxes = myPanel.Controls.OfType<TextBox>();

Enumerable.OfType 将相应地过滤和投射控件.如果你想过滤更多,你可以使用Enumerable.Where,例如:

Enumerable.OfType will filter and cast the controls accordingly. If you want to filter them more, you could use Enumerable.Where, for example:

var myTextBoxes = myPanel.Controls
                         .OfType<TextBox>()
                         .Where(txt => txt.Name.ToLower().StartsWith("e"));

现在你可以迭代那些TextBoxes,例如:

Now you can iterate those TextBoxes, for example:

foreach(TextBox txt in myTextBoxes)
{
    String text = txt.Text;
    // do something amazing
}

编辑:

TextBox 位于多个 TabPage 上.另外,名字有点更合乎逻辑...

The TextBoxes are on multiple TabPages. Also, the names are a little more logical ...

当控件位于多个标签页时,此方法也适用,例如:

This approach works also when the controls are on multiple tabpages, for example:

var myTextBoxes = from tp in tabControl1.TabPages.Cast<TabPage>()
                  from panel in tp.Controls.OfType<Panel>()
                  where panel.Name.StartsWith("TextBoxGroup")
                  from txt in panel.Controls.OfType<TextBox>()
                  where txt.Name.StartsWith("e")
                  select txt;

(请注意,我添加了另一个条件,即面板名称必须以 TextBoxGroup 开头,只是为了表明您也可以组合这些条件)

(note that i've added another condition that the panels names' must start with TextBoxGroup, just to show that you can also combine the conditions)

当然可以根据需要更改检测相关控件的方式(例如使用RegularExpression).

Of course the way to detect the relevant controls can be changed as desired(f.e. with RegularExpression).

这篇关于从多个 TextBox 元素获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆