开发者

Convert combobox string value to int

开发者 https://www.devze.com 2022-12-30 01:07 出处:网络
I ha开发者_开发技巧ve a question about converting types. I want to change the currently selected combobox value string to an int, but I get errors

I ha开发者_开发技巧ve 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?


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.


TryParse is a good method for this sort of thing:

int value;
if (!Int32.TryParse(this.comboBoxNumeric.Text, out value))
{
    //Do something fun...
}


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 DataSets, develop is very easy for C# program.


        try
        {
            string name = comboBoxPort.SelectedItem.ToString();
            int portBaudrate = Convert.ToInt32(comboBoxBaudrate.SelectedItem);
        }

//just solved //enjoy

0

精彩评论

暂无评论...
验证码 换一张
取 消