An exception occured. Exception is specified cast is not valid
int s = (int)comboBox1.SelectedItem;
An exception occured. Exception is specified cast is not valid
int s = (int)comboBox1.SelectedItem;
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.
You're trying to cast a ComboBox Item to an int.
Try int s =(int) comboBox1.SelectedIndex if you want the index of the item.
If you want to get the value that is displayed in the combo box, maybe you should try :
int s = (int)comboBox.SelectedValue;
You require to cast your comboBox1.SelectedItem
in the type with which your binding
by default its of Type Object
For example
System.Data.DataSet ds = new System.Data.DataSet();
ds = Database.Read("select * from [TaskTimer$]");
cbClient.SelectedIndex = -1;
cbClient.DataSource = ds.Tables[0];
cbClient.DisplayMember = "CLIENTS";
cbClient.ValueMember = "CLIENTS";
...
... The user can do stuff like select a Client from the ComboBox DropDown
...
string sSelectedClient = cbClient.SelectedItem.ToString();
As show above I bound datatable with the item so that it gives me error when I am qurying data directly
so to get the item I have to cast like as below
string sSelectedClient = ((DataRowView)cbClient.SelectedItem).Row("CLIENTS")
hope that you will get proper idea by above example
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
}