通过代码批量修改winform中控件相关属性,如通过代码批量设置button按钮的尺寸,参考方法如下:
方法1:所有button统一设置
//设定所有button按钮属性
private void SetAllButton()
{
//把所有按钮添加到List集合
List<Control> buttonList = new List<Control>();
foreach (Control con in Controls)
{
//判断控件类型是否为按钮
if (con is Button)
{
buttonList.Add(con);
}
}
//遍历所有List,设定属性
for (int i=0;i<buttonList.Count; i++)
{
Button btn = buttonList[i] as Button;
btn.Size = new Size(100, 25);
}
}
方法2:只设定含有特定名称的button控件的属性
//设定所有button名称为btn1、btn2、btn3...的按钮属性
private void SetAllBtn()
{
//创建
List<Control> btnList = new List<Control>();
//检索出所有符合名称的按钮控件
for (int i = 0; i < 100; i++)
{
//由于control.Find返回值为一个集合[],利用集合数量≥1代表检索成功
Control[] conBtn = this.Controls.Find("btn" + i.ToString(), false);
if (conBtn.Count() >= 1)
{
//判断控件类型是否为按钮
if (conBtn[0] is Button)
{
btnList.Add(conBtn[0]);
}
}
}
//遍历所有List,设定属性
for (int j = 0; j< btnList.Count; j++)
{
Button btn = btnList[j] as Button;
btn.Size = new Size(150, 50);
}
}