C# DataGridView 通过Model 直接定义字段(您不用再设计器中添加字段了)
作者:互联网
//取属性上的自定义特性给DataGridView赋值 Type objType = typeof(Models.Model); foreach (PropertyInfo propInfo in objType.GetProperties()) { object[] objAttrs = propInfo.GetCustomAttributes(typeof(OperationModel.AttributeClass.ModeProperty), true); if (objAttrs.Length > 0) { OperationModel.AttributeClass.ModeProperty attr = objAttrs[0] as OperationModel.AttributeClass.ModeProperty; if (attr != null) { if (attr.IsVerify) { continue; } DataGridViewTextBoxColumn dgvtxtc = new DataGridViewTextBoxColumn(); dgvtxtc.Name = propInfo.Name; dgvtxtc.DataPropertyName = propInfo.Name; dgvtxtc.HeaderText = attr.PropertyName; this.dataGridView2.Columns.Add(dgvtxtc); } } }
特性的写法
/// <summary> /// 字段属性 /// </summary> [AttributeUsage(AttributeTargets.Property, Inherited = true)] public class ModeProperty : Attribute { private ModeProperty() { } public string PropertyName { get; set; } public Boolean IsNull { get; set; } /// <summary> /// 验证字段 /// </summary> public Boolean IsVerify { get; set; } public Boolean IsList { get; set; } public Type Type { get; set; } public ModeProperty(string PropertyName) { this.PropertyName = PropertyName; } }
标签:ModeProperty,set,get,C#,PropertyName,DataGridView,器中,dgvtxtc,public 来源: https://www.cnblogs.com/LuoCore/p/14986167.html