Reputation: 35
I have two lines of code which are giving me errors:
private void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (combobox1.SelectedValue)
{
case 0:
var item = items.Where(category => category.CategoryIndex == 0);
foreach (var i in item)
{
listbox.Items.Add(new Items { CategoryIndex = i.CategoryIndex, ItemDesc = i.ItemDesc, ItemName = i.ItemName });
}
break;
case 1:
item = items.Where(category => category.CategoryIndex == 1);
foreach (var i in item)
{
listbox.Items.Add(new Items { CategoryIndex = i.CategoryIndex, ItemDesc = i.ItemDesc, ItemName = i.ItemName });
}
break;
Heres the second :
private void listbox_SelectedIndexChanged(object sender, EventArgs e)
{
var item = items.Where(category => category.CategoryIndex == listbox.SelectedValue && (itemName => itemName.ItemName == listbox.SelectedItem.ToString()));
listbox.Text = item.ItemName;
desrciption_label.Text = item.ItemDesc;
}
The error in the first code is at
switch (combobox.SelectedValue)
The error states that:
A switch expression or case label must be bool, char, string, integral, enum, or corresponding nullable type_
The error in the second code is at
category.CategoryIndex == listbox.SelectedValue
This error states that:
Operator '==' cannot be applied to operands of type 'int' and 'object'
How to fix these?
NOTE: There is more a lot code to this, since it's so big I'm leaving it out but if the previous code is needed, please inform me of this
Upvotes: 0
Views: 150
Reputation: 704
In both cases, you will need to cast that combobox.SelectedValue
to something else, i.e.
int choice = (int)combobox.SelectedValue;
depending on whatever type of thing SelectedValue
is.
This is because combobox.SelectedValue
is an object
, so you need to cast it to your data type. See here for details on ComboBox properties.
Upvotes: 3
Reputation: 2110
The errors are self-explanatory.
The first comes from SelectedValue
returning an Object
, which is not allowed in a switch
-statement. You should most likely use SelectedIndex
.
Second means that you can't compare int
with Object
.
CategoryIndex
is an int
, and you can't compare it to SelectedValue
, which is an object, like in the first case. Again using SelectedIndex
should fix it.
If the SelectedValue
is in fact the property you should be using (after databinding for example), cast the object to an int to get proper types (or parse).
Upvotes: 1
Reputation: 2739
[BrowsableAttribute(false)]
[BindableAttribute(true)]
public ***object*** SelectedValue { get; set; }`
See here for more.
You are passing in an object
to the switch, but the cases are integers. You need to resolve that selected value to an integer. Perhaps a straight cast will work but I don't know what is in that combobox.
Upvotes: 1