问题: 假如有一种情况会使用到大量的textbox但是一个一个填充又过于麻烦,我们应该用什么样的方法实现批量快速填充textbox呢?
答:我们会使用到一个类名为Control
这是我们需要填充的图
如下代码嗯我的是方法,
解释:其中 Val数组存的是指 Keys数组存的键,我们外层通过一个foreach循环整体遍历当前界面的所有控件,然后循环内部有一个if用于判断控件是否为textbox,如果是的话执行填充动作。
int i = 0;
foreach (Control ctr in this.Controls)//可以批量填充textbox
{
if (ctr.GetType() == typeof(TextBox))//判断是否为textbox
{
ctr.Text = Val[i];
if (i > keys.Length)
break;
i++;
}
}
效果图:
但是当我们运行这段代码后发现填充的文本竟然是倒序的这是为什么呢?
答:请看如下代码:
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.textBox4 = new System.Windows.Forms.TextBox();
this.textBox5 = new System.Windows.Forms.TextBox();
this.textBox6 = new System.Windows.Forms.TextBox();
这样定义的控件,是这样加入到控件数组的
this.Controls.Add(this.textBox6);
this.Controls.Add(this.textBox5);
this.Controls.Add(this.textBox4);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
懂了吧桟式结构,所以遍历时是从顶部向底部遍历,所以就产生了倒序的效果!那我们如何将倒序改为正序呢?
如果你对填充顺序没有要求,使用此方法即可!但是如果你想从小到大依次填充则需要另辟蹊径!
以下是我的思路:我们这次改为for循环依次调用Controls并将textbox值分别赋为textbox1~textboxd
然后再依次赋值就OK了我们再看一下效果图.
for (int d = 1; d < keys.Length; d++)
{
this.Controls["textBox" + d.ToString()].Text = Val[d - 1];
}
效果图如下: