前言
最近在写一个小软件,需要将控件属性读取配置文件并写入控件属性
代码示范(简化版)
string t1Name = "TextBox1";
string t1Text = "1235";
string c2Name = "CheckBox1";
string c2Checked = "True";
Control[] t1lList = this.Controls.Find(t1Name, true); //查找当前Form窗口中所有控件名为t1Name字符串变量中内容的控件
if (t1lList.Length > 0)
{
Control con1 = t1lList[0]; //将找到的控件实例化到con1
if (con1 is TextBox)
{
con1.Text = Convert.ToString(t1Text);
}
}
Control[] c2lList = this.Controls.Find(c2Name, true); //查找当前Form窗口中所有控件名为c2Name字符串变量中内容的控件
if (c2lList.Length > 0)
{
Control con2 = t1lList[0]; //将找到的控件实例化到con2
if (con2 is CheckBox)
{
((CheckBox)con).Checked = Convert.ToBoolean(c2Checked);
}
}
看懂了吗?
实际应用中我们在读取到配置文件后一般会封装一个struct或者class,里面放对应的属性数据
然后将这个struct或者class声明为List < T > 数组
这样我们在读取数据的时候只需要用foreach进行拆包就可以了
代码样例(完整代码)
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace GkongKongShanJian
{
struct CtrOption
{
public string Name { get; set; }
public object Value { get; set; }
}
public partial class MainForm : Form
{
private list<CtrOption) CtrList; //配置数据数组(需要自己写代码赋值)
private void R3ReadOptionData()
{
string rName = string.Empty;
object rValue = string.Empty;
foreach (CtrOption co in CtrList) //拆包
{
rName = co.Name;
Control[] CtrlList = this.Controls.Find(rName, true);
if (CtrlList.Length > 0)
{
Control con = CtrlList[0];
if (con is TextBox)
{
con.Text = Convert.ToString(co.Value);
}
if (con is ComboBox)
{
((ComboBox)con).SelectedIndex = Convert.ToInt32(co.Value);
}
if (con is CheckBox)
{
((CheckBox)con).Checked = Convert.ToBoolean(co.Value);
}
}
}
}
}
}
看懂了吗?