Winform实现通过特性,实现自动绑定到DataGridTable

首先我们需要定义特性DataGridAttribute

    [AttributeUsage(AttributeTargets.Property)]
    public class DataGridAttribute : Attribute
    {
        public string HeaderName { get; }
        public bool ReadOnly { get; }
        public bool Visable { get; }
        public DataGridAttribute(string headerName, bool readOnly, bool visable)
        {
            HeaderName = headerName;
            ReadOnly = readOnly;
            Visable = visable;
        }
    }

定义3个特性,显示到datagird上的名字,是否只读,是否显示
我们这边定义个用户的Model,如下:

   [SugarTable("drfuser")]
   public class UserModel : BaseInfoModel
   {
       [DataGrid("登录名", true, true)]
       public string LoginName { get; set; } = string.Empty;

       [DataGrid("用户名", true, true)]
       public string NickName { get; set; } = string.Empty;

       [DataGrid("密码", true, false)]
       public string Password { get; set; } = string.Empty;

       [DataGrid("角色", true, true)]
       public UserRole Role { get; set; }

       [DataGrid("访问凭证", true, false)]
       public string Token { get; set; } = string.Empty;

       [DataGrid("邮箱", true, true)]
       public string Mail { get; set; } = string.Empty;

   }

在每个属性上定义特性内容

最后我们绑定DataGridview的时候使用反射来获得属性并绑定到DataGridview
如下:

 public void SetDataGrid()
 {
     if (Data == null)
         return;
     if (Data.Count <= 0)
         return;

     dgview.DataSource = Data;
     var model = Data[0];
     if (model == null)
         return;

     Type property = model.GetType();
     var list = property.GetProperties().ToList();
     int index = 0;
     foreach (var item in list)
     {
         string name = item.Name;
         DataGridAttribute? attribute = (DataGridAttribute?)item.GetCustomAttribute(typeof(DataGridAttribute));
         if (attribute != null)
         {
             dgview.Columns[index].HeaderCell.Value = attribute.HeaderName;
             dgview.Columns[index].Visible = attribute.Visable;
             dgview.Columns[index].ReadOnly = attribute.ReadOnly;
             dgview.Columns[index].DataPropertyName = name;
         }
         index++;
     }
     dgview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

     if (Data.Count > 1000)
         dgview.RowHeadersWidth = 80;
     else if (Data.Count > 10000)
         dgview.RowHeadersWidth = 90;
     else if (Data.Count > 100000)
         dgview.RowHeadersWidth = 100;
     else if (Data.Count > 1000000)
         dgview.RowHeadersWidth = 110;
     else
         dgview.RowHeadersWidth = 70;

     if (dgview.Rows != null)
     {
         int lastCount = (CurrentPageIndex - 1) * PageSize + 1;
         for (int i = 0; i < dgview.Rows.Count; i++)
         {
             dgview.Rows[i].HeaderCell.Value = (i + lastCount).ToString();
         }
     }
 }

你可能感兴趣的:(c#)