在最近做项目中,需要给界面上的所有控件分别赋值,一般的情况是将对应的控件放到控件数组中,再循环赋值,但是也比较麻烦,因此思考能否在winform界面上给控件命名之后,通过string类型直接循环读取对应控件一一进行赋值,这样会省事很多。具体代码如下:
1、String转为Control方法
/// <summary>
/// 字符串转换为相关函数
/// </summary>
/// <param name="controlName">控件名称</param>
/// <param name="controlCollection">界面上全部的控件</param>
/// <param name="control">返回的控件变量</param>
/// <returns>转换是否成功</returns>
public static bool StringToControl(string controlName, Control.ControlCollection controlCollection, out Control control)
{
bool ret = false;
Control[] foundControls = controlCollection.Find(controlName, true);
control = new Control();
if (foundControls.Length > 0)
{
ret = true;
control = foundControls[0];
}
return ret;
}
以上的逻辑是使用Control.ControlCollection类中的.Find()函数进行对应名称的查找,找到的结果直接就是对应的那个控件类型;
形参中的Control.ControlCollection controlCollection,是控件的集合类型,在传参时,需要将调用函数界面中的所有控件传入,一般传this.Controls进去。
2、函数的调用
在这里使用实时显示IO进行一个调用的实例展示
private void IOState()
{
short state, inputNum = 25;
try
{
while (true)
{
Control control = null;
#region Input
for (ushort i = 1; i < inputNum; i++)//i的值需要根据到时候具体的IO进行更改
{
if (!Tool.StringToControl("IN" + i, Controls, out control))
{
continue;
}
UILight control1 = (UILight)control;
state = DataLayer.DataTransfer.Input[i - 1];
if (state == 0)//低电平
{
control1.State = UILightState.Off;
}
else if (state == 1)//高电平
{
control1.State = UILightState.On;
}
}
#endregion
#region Output
for (ushort i = 1; i < inputNum; i++)//i的值需要根据到时候具体的IO进行更改
{
if (!Tool.StringToControl("OUT" + i, Controls, out control))
{
continue;
}
UILight control1 = (UILight)control;
state = DataLayer.DataTransfer.Output[i - 1];
if (state == 0)//低电平
{
control1.State = UILightState.Off;
}
else if (state == 1)//高电平
{
control1.State = UILightState.On;
}
}
#endregion
Thread.Sleep(50);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
因为在界面中,我把相应的控件名称都改为了统一前缀的IN或者OUT,在循环时,只需要遍历即可赋值。