I have a small question about VB.net in Visual studio. I'm loading a combobox using:
cbxAutofit.DataSource = [Enum].GetValues(GetType(DataGridViewAutoSizeColumnsMode))
I want on item.select to apply that "DataGridViewAutoSizeColumnsMode" to a DataGridView on th same form but i'm not doing something right, because when I use the code below, I get the error Unhandled exception. How can I convert the resulting strint to that system enum? Or is there a way I can add the integer value of each DataGridViewAutoSizeColumnsMode as either a second column or something similar, so I can call it?
Dim value As String, Res As DataGridViewAutoSizeColumnsMode
value = cbxSheets.SelectedItem.value
Res = [Enum].Parse(GetType(DataGridViewAutoSizeColumnsMode), value)
CodePudding user response:
Take a look at the Enum documentation's Iterating Enumeration Members section (documentation):
You can call the GetNames method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the Parse method to convert the string to its equivalent enumeration value.
Take a look at this example:
Dim t = GetType(DataGridViewAutoSizeColumnsMode)
cbxAutofit.DisplayMember = "Name"
cbxAutofit.ValueMember = "Value"
cbxAutofit.DataSource = [Enum].GetNames(t).Select(Function(name) New With {.Name = name, .Value = DirectCast([Enum].Parse(t, name), DataGridViewAutoSizeColumnsMode)}).ToList()
Then you can get the value by using:
Dim enumValue = DirectCast(cbxAutofit.SelectedValue, DataGridViewAutoSizeColumnsMode)
CodePudding user response:
Using a string as the DataSource
is fine, but you need to change a couple things:
- You had referenced another
ComboBox
,cbxSheets
, and I guess it's just a typo - You are accessing the
ComboBox.SelectedItem.Value
instead of justSelectedItem
this is fine:
cbxAutoFit.DataSource = [Enum].GetValues(GetType(DataGridViewAutoSizeColumnsMode))
Use SelectedItem
, and access the proper ComboBox
. Also casting to DataGridViewAutoSizeColumnsMode
, and getting the string with ToString()
will get you the correct types.
Private Sub cbxAutoFit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxAutoFit.SelectedIndexChanged
Dim value = cbxAutoFit.SelectedItem.ToString()
Dim resultEnum = DirectCast([Enum].Parse(GetType(DataGridViewAutoSizeColumnsMode), value), DataGridViewAutoSizeColumnMode)
Dim resultText = resultEnum.ToString()
End Sub
The @David solution is fine too. Compared with this, it front-loads the work vs. back-loading it. I do like that approach where the DataSource.Value
is actually a DataGridViewAutoSizeColumnsMode
.