使用c#windows窗体组合框将外键数据插入SQL Server

本文关键字:数据 插入 SQL Server c#windows 窗体 组合 使用 | 更新日期: 2023-09-27 18:26:40

我在SQL Server 2012中创建了两个表ItemListSalt

我想用C#创建一个winforms应用程序。

Salt(父表)

Salt_ID int NOT NULL,   (primary Key)
Salt_Name var

ItemList(子表)

Item_ID int NOT NULL,    (primary Key)
Salt_ID int NOT NULL,    (foreign Key)
Item Name var

组合框绑定细节

Datasource = SaltBindingSource
DisplayMember = Salt_Name  (from `Salt` table)
Value Member = Salt_ID     (primary key)
Selected Value = itemListBindingSource-Salt_ID (Foreign Key in Child table)`

现在我想将组合框主键数据插入子表外键列,我的语句是

(SqlCommand query = new SqlCommand("Insert into Itemlist(Item_Name,Packing,Salt_ID) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.comboBox1.SelectedValue+ "')", con);)`

在这个声明之后,我得到一个错误

System.Data.dll中发生类型为"System.Data.SqlClient.SqlException"的未处理异常
附加信息:将varchar值"Salt_ID"转换为数据类型int时转换失败。

因此,请告诉我如何将数据插入SQL Server数据库表外键列

使用c#windows窗体组合框将外键数据插入SQL Server

将这些值设置为组合框:

classTeacher_Combobox.DisplayMember = "teacher_username";
classTeacher_Combobox.ValueMember = "teacher_id";

Insert into Class(item1,item2,teacher_id) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + classTeacher_Combobox.SelectedValue + "')", con)