tags:

views:

118

answers:

2

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?

A: 

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.

Yoda
all of them are numbers but the error is like that "Object reference not set to an instance of an object."
aslı
on what? the age.SelectedItem? Post the relevant code and I will have a look.What your error is saying is that nothing is selected in the combo box; check you have selected a value in the combo box
Yoda
what can I do for this problem I get same error with the codes you have written
aslı
Any joy with that solution? I have changed the code above.
Yoda
Thank you very much the problem is solved I tried and to see that it works I made addition ,it worked
aslı
No problem :) glad we sorted it
Yoda
@Yoda He never answered me -- is this C# after all? I'd like to tag the question properly, but I don't know the language so I'm not sure, it just looked kind of like it
Michael Mrozek
Yes it is, sorry didnt see your comment last night
Yoda
A: 

why not use a Convert.ToInt32 method?

you can always use the databinding like this:


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.ToInt32(cbo.SelectedValue);
A a = (A) cbo.SelectedItem;
int a_id = a.ID;
int a_name = a.Name;

if you use Linq To Data, develop is very easy for c/s program.

Tim Li