我做了一个应用程序,你可以输入物品进入食品数据库。其中一个输入字段是类型。这是一个单独的表,并用于选择食品类型组合框中填充该表。这就是表如下所示:
类型
---------------------
| id (PK) | name |
---------------------
| int | varchar |
---------------------
食品
-------------------------------------------------
| fid (PK) | fname | typeid (FK:id) | price |
-------------------------------------------------
| int | varchar | int | decimal |
-------------------------------------------------
这是填充组合框(TypeCB是组合框的名称)的代码:
TypeCB.ItemsSource = db.types.ToList();
这是一个不工作的代码:
Food theFood = new Food();
Type theType = new Type();
theFood.name = NameText.Text;
theFood.typeid = Convert.ToInt32(TypeCB.SelectedValue);
theFood.price = Decimal.Parse(PriceText.Text);
db.Voers.InsertOnSubmit(hetVoer);
db.SubmitChanges();
我在做什么错在这里?我得到的错误:
theFood.typeid = Convert.ToInt32(TypeCB.SelectedValue);
错误:
System.InvalidCastException:“无法转换对象WPF App1.type的类型System.IConvertible。”
它看起来像你没有指定DisplayMember
和ValueMember
性能。尝试指定的,看看有没有什么帮助,如:
TypeCB.ItemsSource = db.types.ToList();
TypeCB.ValueMember= "id";
TypeCB.DisplayMember = "name";
我不知道没有指定什么将在SelectedValue
物业未来的价值,可能type
实例的完整的对象。
否则,使用SelectedItem
的解决方法:
Type objType = TypeCB.SelectedItem;
theFood.typeid = objtype.id;
假设type
类有fid
持有物业的ID。