DataGridView linked to DataTable with Combobox column based on enum

后端 未结 3 1392
陌清茗
陌清茗 2020-12-19 17:22

Having spent a lot of yesterday searching on this one I have to give up.

I have a DataGridView linked to a Datatable. One of the columns is an enum and I want that t

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 18:03

    i had this problem myself, here is how i fixed it:

     DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
     col.ValueType = typeof(MyEnum);
     col.ValueMember = "Value";
     col.DisplayMember = "Display";
     colElementtyp.DataSource = new MyEnum[] { MyEnum.Firstenumvalue, MyEnum.Secondenumvalue }
         .Select(value => new { Display = value.ToString(), Value = value })
         .ToList();
    

    the DataGridViewComboBoxCell has to be bound to the enum or integer. I guess the column of your datatable is integer, then it should work.

    EDIT:

    this should work dynamic:

     System.Array enumarray = Enum.GetValues(typeof(MyEnum)); 
     List lst = enumarray.OfType().ToList();
     DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
         col.ValueType = typeof(MyEnum);
         col.ValueMember = "Value";
         col.DisplayMember = "Display";
         colElementtyp.DataSource = lst 
             .Select(value => new { Display = value.ToString(), Value = value })
             .ToList();
    

    shorter:

     DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
     col.ValueType = typeof(MyEnum);
     col.ValueMember = "Value";
     col.DisplayMember = "Display";
     colElementtyp.DataSource = Enum.GetValues(typeof(MyEnum)).OfType().ToList() 
             .Select(value => new { Display = value.ToString(), Value = value })
             .ToList();
    

提交回复
热议问题