Reputation: 993
I am trying to store and retrieve a ContentAlignment
Enum in My.Settings via a combobox. I have setup this Type in Project Settings. I'm populating a combobox on a settings form with the relevant Enum values:
With ControlAnchorCB
.Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
End With
I then try to set the combobox to the one in My.Settings:
ControlAnchorCB.SelectedItem = My.Settings.ConnectorControlAnchor
but no value shows. I also try to save the selected combobox value back to My.Settings with:
My.Settings.ConnectorControlAnchor = ControlAnchorCB.SelectedItem
However, this results in an exception: "System.InvalidCastException: 'Conversion from string "MiddleCenter" to type 'Integer' is not valid.'"
Update: Another limitation is that I'm coding in Framework 3.5 (has to be this version) and vb.net. Thus, Enum.TryParse is not available.
How can I achieve this?
Upvotes: 0
Views: 123
Reputation: 993
After much faffing about solved it:
' My.Settings.ConnectorControlAnchor Type is set to ContentAlignment in Project Settings.
Public Function TryParse(Of TEnum As {Structure, IConvertible})(ByVal value As String, <Out> ByRef result As TEnum) As Boolean
Dim retValue = If(value Is Nothing, False, [Enum].IsDefined(GetType(TEnum), value))
result = If(retValue, CType([Enum].Parse(GetType(TEnum), value), TEnum), Nothing)
Return retValue
End Function
' Populate ComboBox
With ControlAnchorCB
.Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
End With
' Set combobox to value in My.Settings
Dim ca As New ContentAlignment
ControlAnchorCB.SelectedIndex = ControlAnchorCB.FindStringExact(My.Settings.ConnectorControlAnchor.ToString)
' To save value of combobox to My.Settings
Dim ca As New ContentAlignment
If TryParse(Of ContentAlignment)(ControlAnchorCB.SelectedItem, ca) Then My.Settings.ConnectorControlAnchor = ca
Upvotes: 0