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

 

特性的寫法this

  /// <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;
        }
    }
相關文章
相關標籤/搜索