Adding enum to combobox

前端 未结 2 1400
说谎
说谎 2021-02-20 11:48

Hi may i know how to get the enum value below to bind into the combobox? I wrote the below code which works well but wonder is this the best way.

public enum Cou         


        
相关标签:
2条回答
  • 2021-02-20 12:25

    I don't think there is a best way. I used to do something similar with a GenericListItem<T> class where T is the backing value, in your case, an enum.

    This class exposed Display string and Value T properties to bind to. I think I was also overriding ToString because it is the default if you don't specify the DisplayMember. I went further and made a constructor taking just Value and defaulting Display to Value.ToString, which in the case of enums works I think.

    I'd then make a List<GenericListItem<T>>, feed that into the DataSource of the column and set the DisplayMember and ValueMember properties accordingly in code. This list is the alternative to the dictionary used in your example.

    But I'm not saying it's a better solution :-) however it means you can remove code, say enum iteration, into this class or specialise the class for handling certain data types better, all with the end goal of being inserted into a list and bound to a control.

    0 讨论(0)
  • 2021-02-20 12:41

    Following should be the simplest way to bind it.

    column.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
    

    To get the selected value you need to cast it to the enum type.

    CourseStudentStatus selectedValue = (CourseStudentStatus)column.SelectedValue
    

    Enum.GetValues returns an array of the enumType values which can then be bound to any control.

    I've tested this on a standalone combobox, not in a combobox column in DataGridView, YMMV.

    0 讨论(0)
提交回复
热议问题