C# Winform 根据提供的控件名字符串写入对应的数据的数据

前言

最近在写一个小软件,需要将控件属性读取配置文件并写入控件属性

代码示范(简化版)

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);
                    }
                }
            }
        }

    }
}

看懂了吗?

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工控闪剑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值