问题描述
假设我有 10 个文本框,我想在每个文本框中输入相同的文本.我不想写 textBoxNum.Text = "hello!"
十次,所以我可能会这样写:
Say I have 10 text boxes and I want to put the same text into each of them. I don't want to write textBoxNum. Text = "hello!"
ten times so I might write something like this:
for(int i=1; i<=10; i++)
{
textBox + i. Text = "hello!";
}
显然,它不起作用.
如何使用 for
循环来完成此操作?
How can this be done with a for
loop ?
推荐答案
您需要将所有文本框加载到列表或数组结构中,这将允许您对其进行迭代.
You either need to load all of your textboxes into a list or array structure, and this will allow you to iterate over it.
TextBox[] boxes = { tb1, tb2, tb3, ... };
否则,您可以检查表单/容器的 Controls
属性以查找 TextBox
类型的项目.如果控件可以嵌套在更深的容器中,您可能需要递归地探索它们(在这一点上,我会认真考虑使用数组方法,除非您要加载数量惊人的文本框).但作为一个起点,你可能有
Otherwise, you could inspect the Controls
property of your form/container for items of the TextBox
type. If the controls could be nested in deeper containers, you might need to recursively explore them (at this point, I would seriously consider an array approach, unless you have some ghastly number of textboxes to load). But as a starting point, you might have
foreach (var tb in this.Controls.OfType<TextBox>())
{
tb.Text = "whatever";
}
这篇关于通过 for 循环迭代文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!