-1

I have two controls on a Windows Form - A Combobox and a ListBox.

I'm trying to populate the ListBox based on selected value from the ComboBox, but I keep getting the following error.

Unable to cast object of type 'System.Data.Entity.DynamicProxies.Category_B0496327038CB6B25A6EF7B750129DD7B44A87BE41C4E2DB0F8D7A00898B060F' to type 'System.IConvertible'.

public partial class Form1 : Form
{
    NorthWindEntities dbContext = new NorthWindEntities();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cbx_Categories.DataSource = dbContext.Categories.ToList();
        cbx_Categories.DisplayMember = "CategoryName";
        cbx_Categories.ValueMember = "CategoryID";
    }

    private void cbx_Categories_SelectedIndexChanged(object sender, EventArgs e)
    {
        int categoryID = Convert.ToInt16(cbx_Categories.SelectedValue);
        PopulateProductsLbx(categoryID);
    }

    void PopulateProductsLbx(int categoryID)
    {
        var products = from p in dbContext.Products
                       where p.CategoryID == categoryID
                       select p.ProductName;

        lbx_Products.DataSource = products.ToList();
    }
}

What would be my best approach to resolve this? Thank you in advance.

Krishna
  • 2,451
  • 1
  • 26
  • 31
Muad'Dib
  • 520
  • 4
  • 17

1 Answers1

0

Have you thought about trying

int categoryID = ((DataRowView)cbx_Categories.SelectedItem).Row["CategoryID"];

This should handle the casting for you.

  • No good: Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?) – Muad'Dib Jul 10 '15 at 05:46