/// <summary> /// 由数据类型的属性产生列 /// </summary> /// <param name="classType"></param> /// <returns></returns> public static DataGridViewColumn[] GenDataGridViewCols(Type classType) { List <DataGridViewColumn> cols = new List <DataGridViewColumn>(); PropertyInfo[] infos = classType.GetProperties(); foreach (PropertyInfo info in infos) { string name = info.Name; string propertyName = info.Name; string headerText = info.Name; DataGridViewColumn col = null; if (info.PropertyType == typeof(bool)) { col = DataGridViewUtil.CreateBoolCol(name, propertyName, headerText); } else if (info.PropertyType == typeof(byte[])) { col = DataGridViewUtil.CreateImageCol(name, propertyName, headerText); } else { col = DataGridViewUtil.CreateTxtCol(name, propertyName, headerText); } cols.Add(col); } return(cols.ToArray()); }
/// <summary> /// 根据对象的属性建立DataGridView表。 /// </summary> /// <param name="hiddenAttributes">需要隐藏的属性</param> /// <param name="useDisplayName">是否使用属性的Display属性</param> /// <param name="classType">待建表的对象类型</param> /// <returns></returns> public static DataGridViewColumn[] BuildDataGridViewCols(Type classType, bool useDisplayName = false, List <string> hiddenAttributes = null) { if (hiddenAttributes == null) { hiddenAttributes = new List <string>(); } PropertyInfo[] infos = classType.GetProperties(); List <PropertyInfo> oldInfoList = new List <PropertyInfo>(infos); //排序 List <PropertyInfo> infoList = new List <PropertyInfo>(); foreach (string name in NAME_ASC_SORT_LIST) { foreach (PropertyInfo p in infos) { string disName = ObjectUtil.GetDisplayName(p); if (p.Name == name || (p.Name != null && p.Name.Contains(name)) || (disName != null && (disName == name || disName.Contains(name)))) { if (!infoList.Contains(p)) { infoList.Add(p); } } } } //没有排上的添加过来 foreach (PropertyInfo pro in infos) { if (!infoList.Contains(pro)) { infoList.Add(pro); } } List <DataGridViewColumn> cols = new List <DataGridViewColumn>(); foreach (PropertyInfo info in infoList) { if (hiddenAttributes.Contains(info.Name)) { continue; } string name = info.Name; string propertyName = info.Name; string headerText = info.Name; if (useDisplayName) { headerText = ObjectUtil.GetDisplayName(info); if (headerText == null) { continue; } } DataGridViewColumn col = null; if (info.PropertyType == typeof(bool)) { col = DataGridViewUtil.CreateBoolCol(name, propertyName, headerText); } else if (info.PropertyType == typeof(byte[])) { col = DataGridViewUtil.CreateImageCol(name, propertyName, headerText); } else { col = DataGridViewUtil.CreateTxtCol(name, propertyName, headerText); } cols.Add(col); } return(cols.ToArray()); }