Search code examples
c#parsingcombobox

Convert combobox string value to int


I have a question about converting types. I want to change the currently selected combobox value string to an int, but I get errors

My code:

int.Parse(age.SelectedItem.ToString());

What can I do for this problem?


Solution

  • Ok now we know the error, you can check for a null value before trying to parse it using:

        if (comboBox1.SelectedItem != null)
        {
            int x = int.Parse(comboBox1.SelectedItem.ToString());
        }
        else { //Value is null }
    

    You can avoid a null value being passed by setting the text property of the control to what ever default value you want.

    If you are still not getting a value after making sure one is selected you really need to post your code.