【问题标题】:Insert foreign key data into SQL Server using c# windows form combobox使用 c# windows form 组合框将外键数据插入 SQL Server
【发布时间】:2015-12-12 08:45:10
【问题描述】:

我在 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 数据库表的外键列中

【问题讨论】:

  • this.comboBox1.SelectedValue 是一个字符串值。您必须将其转换为 int
  • int.Parse(this.comboBox1.SelectedValue)
  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入
  • 错误 1 ​​'int.Parse(string)' 的最佳重载方法匹配有一些无效的参数
  • 错误 2 参数 1:无法从 'object' 转换为 'string'

标签: c# windows forms sql-server-2012


【解决方案1】:

将这些值设置为组合框:

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)

【讨论】:

  • 现在我想以其他形式在外键上选择 DisplayMember,这怎么可能
  • 你可以使用这个查询:select teacher_username from TableName where teacher_id = ' " +classTeacher_Combobox.SelectedValue + " ' ;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多