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?
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.
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...
vb Code: Dim val As Integer = CInt(myComboBox. SelectedItem)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With