我怎样才能在C#中充满了SQL数据的组合框获取ID?

问题描述 投票:-1回答:1

我做了一个应用程序,你可以输入物品进入食品数据库。其中一个输入字段是类型。这是一个单独的表,并用于选择食品类型组合框中填充该表。这就是表如下所示:

类型

---------------------
| 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。”

c# sql combobox
1个回答
1
投票

它看起来像你没有指定DisplayMemberValueMember性能。尝试指定的,看看有没有什么帮助,如:

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。

© www.soinside.com 2019 - 2024. All rights reserved.