简体   繁体   中英

C# program exception

An exception occured. Exception is specified cast is not valid

int s = (int)comboBox1.SelectedItem;

这意味着组合框项目中的值不是int

检查SelectedIndex> -1或SelectedItem!= null

try

int s = int.Parse(comboBox1.SelectedItem.ToString());

you can not convert any object to an int by just casting. If you have a string you need to use int.Parse() to convert a string to an int .

If you insert your own objects as Items in the combobox you can cast comboBox1.SelectedItem to your type instead.

ComboBox.SelectedItem.ToString() only returns the content if you have inserted string objects in the combobox, a more reliable way is to check the ComboBox.Text property instead. This will also save you from some null checking.

如果你想获得组合框中显示的值,也许你应该尝试:

int s = (int)comboBox.SelectedValue;

Example usage on MSDN here

But really, you need to provide more details in the question :)

Total guess but a common thing to do may be to store a database id in a comboboxes value property and the database item text in the text property. If this is what you are doing then you can use the below syntax if you know for certain that the value of the combobox is always castable to an int.

int i = (int)ComboBox1.SelectedValue.ToString();

or if your not sure it's always an int you can...

try
{
int i = int.Parse(ComboBox1.SelectedValue.ToString());
}
catch
{
//handle the non int situation here
}

or

int i;
bool result = int.TryParse(ComboBox1.SelectedValue.ToString(), out i);

            if (result)
            {
                //you can use the variable i now
            }
            else
            {
                //The parse failed so handle a non int situation here
            }

试试Convert.ToInt32(combo.Items[combo.SelectedIndex].Value.ToString());

int s = comboBox.SelectedIndex

You're trying to cast a ComboBox Item to an int.

Try

int s = comboBox1.SelectedIndex;

if you want the index of the item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM