Winter Winter -4 years ago 74
C# Question

A switch expression and an operator error

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download