Sam Nightwoods Sam Nightwoods - 1 month ago 4
C# Question

Giving unable to convert String to Category Error

I can't seem to be able to filter my list box with my combobox, though the text filter works fine. How can I fix the problem of being unable to convert String to Category?

Part of: StaffListView.xaml

StaffController sc = (StaffController)Application.Current.FindResource("staffcontroller");
public StaffListView()
{
InitializeComponent();
StaffController sc = (StaffController)Application.Current.FindResource("staffcontroller");
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count > 0)
{
//too much going on i think it sees the () as a method because of the ToString
sc.FilterBy(comboBox.SelectedItem.ToString());
//MessageBox.Show("Dropdown list used to select: " + e.AddedItems[0]);
}
}


Part of StaffControler:

public void FilterBy(Category currCategoryFilter)
{
var selected = from Staff s in MasterStaffListBasic
where currCategoryFilter == Category.All || s.StaffCategory == currCategoryFilter
select s;
ViewableStaffList.Clear();
selected.ToList().ForEach(ViewableStaffList.Add);
}


EDIT:
Also just to clarify Category is a public enum defined in the controller

Answer

You've passed a string to the FilterBy method which accepts a category as a parameter. You should pass the comboBox.SelectedItem but cast it to Category like this:

entersc.FilterBy(comboBox.SelectedItem as Category);

Based on your edit that you said Category is a public enum you should pass it like this:

entersc.FilterBy((Category) comboBox.SelectedItem);

Or if you still want to use as operator:

entersc.FilterBy(comboBox.SelectedItem as Category? ?? (Category) 0);

Because the as operator must be used with a reference type or nullable type.

Comments