Question

I have following code

lstLanguage.Items.Add(CultureInfo.GetCultureInfo("en-US").NativeName)
lstLanguage.SelectedIndex = 0

When the below code runs

Dim strLanguageCode As String = CType(lstLanguage.SelectedItem, CultureInfo).NativeName

it throws an exception

System.InvalidCastException:
Unable to cast object of type 'System.String' to type 'System.Globalization.CultureInfo'.

What's wrong on the code

Était-ce utile?

La solution

A string cannot be cast into a CultureInfo, so that is why you are getting an InvalidCastException.

I'm going to guess that what you are trying to achieve is to display a list of native names of cultures and when the user selects one, you want to be able to retrieve the original language code or CultureInfo associated with that. The way this is usually handled is by assigning the CultureInfo to the list and providing a viewer that converts the CultureInfo to a string by way of the NativeName.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top