Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 863
aslı Avatar asked May 14 '10 00:05

aslı


People also ask

How to get integer value from ComboBox in c#?

class A { public int ID{get;set;} public string Name{get;set;} } cbo. DataSource = new A[]{new A{ID=1, Name="hello"}}; cbo. DisplayMember = "Name"; cbo. DisplayValue = "ID"; int id = Convert.

How to get integer value from ComboBox in java?

String text = (String)cb1. getSelectedItem(); int value = Integer. parseInt(text); Alternatively (and arguably, more correctly), you could use a ListCellRenderer , which would allow you to change the way that the values looked when rendered within the JComboBox , something like...

How to Convert ComboBox value to integer in vb net?

vb Code: Dim val As Integer = CInt(myComboBox. SelectedItem)

What is selected item in ComboBox?

When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.


1 Answers

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.

like image 142
Matt Avatar answered Nov 15 '22 04:11

Matt