C#将部分Controls数据导入对象并存入ini中

目录

1.遍历控件和属性得到控件的值

 2.利用FieldInfo的getSet函数设置类对象数据

 3.Ini简易类库编写

 4.存入对象转换为json存入ini

 5.效果展示

在日常的Winform设计工作中,将控件中的数据导出到对应属性或者字段中,再进行保存是经常会用到的技巧;最简单的就是同时遍历控件和遍历属性字段进行名称对比(需要保证控件的名称要包含在字段属性中);

本篇文章主要是在简单的基础上优化整体逻辑,不仅仅是只遍历控件和属性进行名称对比(适合类),还包含一些筛选;

1.遍历控件和属性得到控件的值

 在下面代码中,控件命名是以textBox_one的形式命名的

///类对象
class ObjectParm
    {
        public int one;
        public string two;
        public int three;
        public string four;
        public int five;
        public string six;
    }
private void Save(ObjectParm objectParm, Control controls, string TextName = "textBox_", string ComboBoxName = "comboBox_")
        {
            Type type = objectParm.GetType();
            //获取有关成员属性的信息以及提供对成员数据的访问
            MemberInfo[] memberInfos = type.GetMembers();//获取所有公共成员
            foreach (Control control in controls.Controls)
            {
                foreach (MemberInfo item in memberInfos)
                {
                    //这里字段属性均可以
                    if (item.MemberType == MemberTypes.Field)
                    {
                        if (control is ComboBox)
                        {
                            if (control.Name == ComboBoxName + item.Name)
                            {
                                string value = control.Text;
                                //需要筛选对象属性的类型
                                SetMemberValue(objectParm, item.Name, value);
//---------------------------------注意----------------------------------
//SetMemberValue函数是判断属性或者字段的类型,根据类型进行不同的赋值
                            }
                        }
                        else if (control is TextBox)
                        {
                            if (control.Name == TextName + item.Name)
                            {
                                string value = control.Text;
                                //需要筛选对象属性的类型
                                SetMemberValue(objectParm,item.Name,value);
                            }
                        }
                    }
                }
            }
        }

 2.利用FieldInfo的getSet函数设置类对象数据

/// <summary>
        /// 设置类对象成员数据
        /// </summary>
        /// <param name="objectParm"></param>
        /// <param name="fileName"></param>
        /// <param name="filevalue"></param>
//Istype函数是对比类型是否一致
        private bool SetMemberValue(ObjectParm objectParm, string fileName, string filevalue)
        {
            Type type = objectParm.GetType();
            //发现字段属性并提供访问
            FieldInfo fieldInfo = type.GetField(fileName);//搜索字段
            bool ConverFlag = true;
            //类型匹配
            if (Istype(fieldInfo.FieldType, "System.String"))
            {
                fieldInfo.SetValue(objectParm, filevalue);
            }
            if (Istype(fieldInfo.FieldType, "System.Double"))
            {
                //判断是否可以进行转
                double result = 0;
                if (!double.TryParse(filevalue, out result)) ConverFlag = false;
                fieldInfo.SetValue(objectParm, result);
            }
            if (Istype(fieldInfo.FieldType, "System.Single"))
            {
                float result = 0;
                if (!float.TryParse(fileName, out result))
                    ConverFlag = false;
                fieldInfo.SetValue(objectParm, result);
            }
            if (Istype(fieldInfo.FieldType, "System.Boolean"))
            {
                bool flag = false;
                if (!Boolean.TryParse(fileName, out flag))
                    ConverFlag = false;
                fieldInfo.SetValue(objectParm, flag);
            }
            if (Istype(fieldInfo.FieldType, "System.UInt32"))
            {
                uint value = 0;
                if (!uint.TryParse(fileName, out value))
                    ConverFlag = false;
                fieldInfo.SetValue(objectParm, value);
            }
            if (Istype(fieldInfo.FieldType, "System.UInt16"))
            {
                UInt16 value = 0;
                if (!UInt16.TryParse(fileName, out value))
                    ConverFlag = false;
                fieldInfo.SetValue(objectParm, value);
            }
            if (Istype(fieldInfo.FieldType, "System.Int32"))
            {
                int value = 0;
                if (!Int32.TryParse(fileName, out value))
                    ConverFlag = false;
                fieldInfo.SetValue(objectParm, value);
            }
            if (Istype(fieldInfo.FieldType, "System.Decimal"))
            {
                if (filevalue != "")
                    fieldInfo.SetValue(objectParm, Decimal.Parse(filevalue));
                else
                    fieldInfo.SetValue(objectParm, new Decimal(0));
            }
            if (Istype(fieldInfo.FieldType, "System.Nullable`1[System.DateTime]"))
            {
                if (filevalue != "")
                {
                    try
                    {
                        fieldInfo.SetValue(objectParm, (DateTime?)DateTime.ParseExact(filevalue, "yyyy-MM-dd HH:mm:ss", null));
                    }
                    catch
                    {
                        fieldInfo.SetValue(objectParm, (DateTime?)DateTime.ParseExact(filevalue, "yyyy-MM-dd", null));
                    }
                }
                else
                    fieldInfo.SetValue(objectParm, null);
            }

            return ConverFlag;
        
        }
private bool Istype(Type type, string typeName)
        {
            if (type.ToString() == typeName)
            { return true; }
            if (type.ToString() == "System.Object")
                return false;
            return Istype(type.BaseType, typeName);
        }

 3.Ini简易类库编写

class IniClass
    {
        public static string inipath = Directory.GetCurrentDirectory() + "\\" + "systemset.ini";//这个地方实际没用到,在另外一个地方
        [System.Runtime.InteropServices.DllImport("kernel32")]
        public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [System.Runtime.InteropServices.DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        public IniClass(string inipath_)
        {
            inipath = inipath_;
        }


        /// ﹤summary﹥   /// 写入INI文件   /// ﹤/summary﹥   /
        // ﹤param name="Section"﹥项目名称(如 [TypeName] )﹤/param﹥   
        /// ﹤param name="Key"﹥键﹤/param﹥   
        /// ﹤param name="Value"﹥值﹤/param﹥   
        public void IniWriteValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, inipath);
        }

        /// ﹤summary﹥   
        /// 读出INI文件   
        /// ﹤/summary﹥   
        /// ﹤param name="Section"﹥项目名称(如 [TypeName] )﹤/param﹥   
        /// ﹤param name="Key"﹥键﹤/param﹥   
        public string IniReadValue(string Section, string Key, string default_value = "")
        {
            StringBuilder temp = new StringBuilder(50000);
            int i = GetPrivateProfileString(Section, Key, default_value, temp, 50000, inipath);
            return temp.ToString();
        }

 4.存入对象转换为json存入ini

string Path = @"E:\ymx\Test\将部分Controls数据导入对象\sys.ini";
        private void button1_Click(object sender, EventArgs e)
        {
            Save(objectParm,panel1, "textBox_", "comboBox_");
            string str = JsonConvert.SerializeObject(objectParm);
            //存入ini
            IniClass iniClass = new IniClass(Path);
            iniClass.IniWriteValue("Parm", "trest", str);

         }

 5.效果展示

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

薄荷撞~可乐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值