Create drop down list options from enum in a DataGridView

前端 未结 2 1249
予麋鹿
予麋鹿 2020-12-06 05:07

I currently have a class and I\'m trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the at

相关标签:
2条回答
  • 2020-12-06 05:16

    I do not know if that would work with a DataGridView column but it works with ComboBoxes:

    comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
    

    and:

    MyEnum value = (MyEnum)comboBox1.SelectedValue;
    

    UPDATE: It works with DataGridView columns too, just remember to set the value type.

    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
    col.Name = "My Enum Column";
    col.DataSource = Enum.GetValues(typeof(MyEnum));
    col.ValueType = typeof(MyEnum);
    dataGridView1.Columns.Add(col);
    
    0 讨论(0)
  • 2020-12-06 05:40

    Or, if you need to do some filtering of the enumerator values, you can loop through Enum.GetValues(typeof(EnumeratorName)) and add the ones you want using:

    dataGridViewComboBoxColumn.Items.Add(EnumeratorValue)
    

    As an aside, rather than using a DataTable, you can set the DataSource of the DataGridView to a BindingSource object, with the DataSource of the BindingSource object set to a BindingList<Your Class>, which you populate by passing an IList into the constructor.

    Actually, I'd be interested to know from anyone if this is preferable to using a DataTable in situations where you don't already have one (i.e. it is returned from a database call).

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