winform 批量控件取值賦值
阿新 • • 發佈:2018-09-19
key typeof 控件取值 tar null inf ati 技術 class
以前寫winform 最多寫幾個文本框,最近需要入錄一個人員信息,那好幾十個字段,一下子幹蒙了,這要是一個個取值賦值都寫到明天了,於是就自己寫了個方法,也不是什麽高大上的,就是很簡單很普通很low的方法。
廢話少說上代碼,註意,這塊我就用了個文本框,你也可以找到所有控件,盡量控件name與實體字段一樣。
public Dictionary<string, object> GetRS_InfoVue() { var dic = new Dictionary<string, object>(); foreachView Code(Control ctl in groupBox1.Controls) { if (ctl is TextBox) { dic.Add(((TextBox)ctl).Name, ((TextBox)ctl).Text); } } return dic; }
根據控件,實體賦值
/// <summary> /// 屬性賦值View Code/// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="keyValues"></param> /// <returns></returns> public static T SetProperties<T>(T t, Dictionary<string, 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; }
根據實體,控件賦值
public static Dictionary<string, string> GetProperties<T>(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 Dictionary<string, 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 批量控件取值賦值