Convert combobox string value to int

ぐ巨炮叔叔 提交于 2019-12-21 21:29:12

问题


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?


回答1:


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.




回答2:


TryParse is a good method for this sort of thing:

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



回答3:


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.



来源:https://stackoverflow.com/questions/2831082/convert-combobox-string-value-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!