Pregunta

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

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top