2015-07-10 132 views
-1

我在Windows窗体上有两个控件 - 一个Combobox和一个ListBox。实体框架Winforms

我想填充列表框,基于从ComboBox中选定的值,但我不断收到以下错误。

无法转换类型 'System.Data.Entity.DynamicProxies.Category_B0496327038CB6B25A6EF7B750129DD7B44A87BE41C4E2DB0F8D7A00898B060F' 的目的为类型 '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(); 
    } 
} 

什么是解决这个我最好的方法呢? 预先感谢您。

+0

请参阅http://stackoverflow.com/questions/6901070/getting-selected-value-of-a-combobox –

+0

@AllanWoods“ComboBoxItem”在WinForms中不可用 –

+0

您可以尝试明确地说cbx_Categories.SelectedValue.ToString ()。 –

回答

0

你有没有想过尝试

INT的categoryID =((DataRowView的)cbx_Categories.SelectedItem).Row [ “类别ID”];

这应该为你处理铸件。

+0

不好:不能将类型'object'隐式转换为'int'。存在明确的转换(您是否缺少演员?) –