C# DataGridView 通过Model 直接定义字段(您不用再设计器中添加字段了)

2021/7/8 17:08:03

本文主要是介绍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# DataGridView 通过Model 直接定义字段(您不用再设计器中添加字段了)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程