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;
        }
    }

 

上一篇:C# winform单元格的formatted值的类型错误 DataGridView中CheckBox列运行时候System.FormatException异常


下一篇:如何:在 Windows 窗体 DataGridView 控件的单元格中显示图像