我正在尝试使用datagridview组合框制作一个选项列表,该列表正确显示但在选择它时会给出类型/转换错误。它给出字符串,但期望实体类型MyProduct。
错误从System.String转换为MyProduct无效
private void frmtest_Load(object sender, EventArgs e)
{
var products = new BindingList<MyProduct>()
{
new MyProduct(){ID =1,Name="Product1" },
new MyProduct(){ID =2,Name="Product2" },
new MyProduct(){ID =4,Name="Product3" },
new MyProduct(){ID =5,Name="Product4" }
};
MyProduct.DataSource= products;//comboboxcolumn datasource
}
public class MyProduct
{
public MyProduct()
{
}
public int ID { get; set; }
public string Name { get; set; }
public string Specification { get; set; }
public override string ToString()
{
return Name;
}
}
public class MyPurchaseItem
{
public MyPurchaseItem()
{
}
public int ID { get; set; }
public virtual MyProduct MyProduct { get; set; }
public int qty { get; set; }
public decimal Price { get; set; }
}
答案 0 :(得分:0)
阅读各种回复后,设法通过添加返回同一对象的方法来解决此问题。
这需要一个nethod来返回可以分配给ValueMember的对象本身,然后设置displaymember。
public MyProduct()
{
}
public int ID { get; set; }
public string Name { get; set; }
public string Specification { get; set; }
***public MyProduct Self { get { return this; } }***
public override string ToString()
{
return Name;
}
//datagridcombobox changed as below
MyProduct.DataPropertyName = "MyProduct";
MyProduct.ValueMember = "Self";
MyProduct.DisplayMember = "Name";