winform 批量控件取值赋值
标签:efi string star sum param reac lap 分享 inf
以前写winform 最多写几个文本框,最近需要入录一个人员信息,那好几十个字段,一下子干蒙了,这要是一个个取值赋值都写到明天了,于是就自己写了个方法,也不是什么高大上的,就是很简单很普通很low的方法。
废话少说上代码,注意,这块我就用了个文本框,你也可以找到所有控件,尽量控件name与实体字段一样。
public Dictionarystring, object> GetRS_InfoVue()
{
var dic = new Dictionarystring, object>();
foreach (Control ctl in groupBox1.Controls)
{
if (ctl is TextBox)
{
dic.Add(((TextBox)ctl).Name, ((TextBox)ctl).Text);
}
}
return dic;
}
View Code
根据控件,实体赋值
///
/// 属性赋值
///
///
///
///
///
public static T SetProperties(T t, Dictionarystring, object> keyValues)
{
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (var item in propertys)
{
if (keyValues.ContainsKey(item.Name))
{
//否是泛型
if (!item.PropertyType.IsGenericType)
{
if (!string.IsNullOrEmpty(keyValues[item.Name].ToString()))
{
item.SetValue(t, Convert.ChangeType(keyValues[item.Name], item.PropertyType), null);
}
}
else
{
if (!string.IsNullOrEmpty(keyValues[item.Name].ToString()))
{
//泛型Nullable
Type genericTypeDefinition = item.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable))
{
item.SetValue(t, Convert.ChangeType(keyValues[item.Name], Nullable.GetUnderlyingType(item.PropertyType)), null);
}
}
}
}
}
if (keyValues.Count 0)
{
return default(T);
}
return t;
}
View Code
根据实体,控件赋值
public static Dictionarystring, string> GetProperties(T t)
{
string tStr = string.Empty;
if (t == null)
{
return null;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (properties.Length 0)
{
return null;
}
var dic = new Dictionarystring, string>();
foreach (PropertyInfo item in properties)
{
string name = item.Name;
object value = item.GetValue(t, null);
if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (!dic.ContainsKey(name))
{
if (value != null)
{
dic.Add(name, value.ToString());
}
else
dic.Add(name, "");
}
}
}
return dic;
}
View Code
winform 批量控件取值赋值
标签:efi string star sum param reac lap 分享 inf
原文地址:https://www.cnblogs.com/cuichaohui/p/9674541.html
评论