DataGridView linked to DataTable with Combobox column based on enum

后端 未结 3 1385
陌清茗
陌清茗 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 17:53

    I gave up on doing this linking the enum directly to the combox. I thought that Koryu had solved it but while it then worked when a user entered data, if I tried to programmatically add a row, with a valid value for the enum, it still gave the error.

    Based on my above code, with Koryu's change, I added a row like this.

    private void CreateDefaultRows() 
    {
      DataRow Row = DtTbl.NewRow();
      Row["Name"] = "FIN";
      Row["Engine"] = EngineType.EngineType1;
      DtTbl.Rows.Add(Row);
      DGV.DataSource = DtTbl;
    }
    

    But despite debugging to ensure a valid value I still got the error.

    I solved it by using the method of using a datatable. I wrote a generic method in my helper class which returns a datatable for any enum.

        public static DataTable Enum2DataTable()
        {
            DataTable EnumTable = new DataTable();
            EnumTable.Columns.Add(new DataColumn("Value", System.Type.GetType("System.Int32")));
            EnumTable.Columns.Add(new DataColumn("Display", System.Type.GetType("System.String")));
            DataRow EnumRow;
            foreach (T E in Enum.GetValues(typeof(T)))
            {
                EnumRow = EnumTable.NewRow();
                EnumRow["Value"] = E;
                EnumRow["Display"] = E.ToString();
                EnumTable.Rows.Add(EnumRow);
            }
    
            return EnumTable;
        }
    

    If I then add the following line when defining the combo box column in my code in the question everything works fine with no other changes and with no errors.

    EngineCol.DataSource = Enum2DataTable();
    

    While this works, and I have a reusable method to do this again, it still feels like it should have been possible assigning the enum directly to the combo box as that 'almost' works.

    Would love to know why it doesn't work but this solution works at least.

提交回复
热议问题