如何从用C#填充SQL数据的组合框中获取ID?

时间:2019-02-05 08:20:44

标签: c# sql combobox

我制作了一个应用程序,您可以在其中将食物输入食物数据库。输入字段之一是类型。这是一个单独的表,用于选择食物类型的组合框已填充此表。表格如下所示:

类型

---------------------
| 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:'无法将对象WpfApp1.type转换为System.IConvertible类型。'

1 个答案:

答案 0 :(得分: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。