【问题标题】:Add referenced name instead of ID from comobox从组合框中添加参考名称而不是 ID
【发布时间】:2019-06-27 16:59:00
【问题描述】:

我有 2 张桌子。第一个列 (categoryID) 是第二个表中 categoryID 的外键。第二个表有 2 个列 (categoryID, categoryName)。经过一番挣扎后,我在组合框中显示了 categoryName 而不是 categoryID。但是现在,当我想从已经创建的现有 categoryName 中进行选择(显示在组合框中的下拉列表中)时,这是不可能的,因为我必须在那里输入 int 而不是字符串格式。我是编程初学者

con.Open();
        string cmddt = "insert into wallettbl(sum, date, categoryID, type)   
        values ('" + textBox1.Text + "','" + textBox2.Text + "','" + 
        comboBox1.Text + "', '" + type + "')";

        SqlCommand com = new SqlCommand(cmddt, con);
        com.ExecuteNonQuery();

如果我想添加字符串(来自组合框)而不是 int,如何编写代码,但在第一个表中将添加引用到 categoryName 的 categoryID。
编辑:为组合框添加代码

 con.Open();
                string cmddt = "select categoryNAME from categoryTbl";
                SqlCommand com = new SqlCommand(cmddt, con);
                SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                com.ExecuteNonQuery();
                con.Close();

【问题讨论】:

  • 令我惊讶的是,在 2019 年,人们仍在编写易受 SQL injection 攻击的代码。使用参数化查询!
  • 请使用parameters。至于您的问题,组合框中的项目是对象,而 ToString() 返回的任何内容都是显示的值。您可以创建自己的具有 CatagoryID 和 CategoryName(由 ToString() 返回)的类,并将 CatagoryID 属性用作查询参数。
  • 这是什么类型的应用程序? WinForms、WPF、MS Access 和 ASP.NET 之间的 Combobox 略有不同。因此,请标记其中之一(或您正在使用的任何内容)。此外,如果您发布用于填充组合框的代码也会有所帮助。
  • 添加到@JohnWu 的评论中,我在之前的评论中与 WinForms 交谈过。
  • @ZoharPeled 就像我说的我是编程初学者。我将查看参数化查询。谢谢你的回答。

标签: c# winforms combobox


【解决方案1】:

更改查询以加载如下类别:

string cmddt = "select categoryID, categoryNAME from categoryTbl";

设置comboBox1的数据源如下:

comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";

最后修改代码,将数据插入到 wallettbl 中:

string cmddt=
            @"INSERT INTO WALLETTBL(sum, date, categoryID, type)   
    VALUES (@Sum, @Date, @CategoryId, @Type);";

         using (SqlConnection conn = new SqlConnection(ConnectionString))
         {
            using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
            {
               cmd.Parameters.Add("@Sum", SqlDbType.Int).Value = textBox1.Text;
               cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = textBox2.Text;
               cmd.Parameters.Add("@CategoryId", SqlDbType.Int).Value =  Convert.ToInt32(comboBox1.SelectedValue);
               cmd.Parameters.Add("@Type", SqlDbType.Varchar).Value = type;
               await conn.OpenAsync();
               await cmd.ExecuteNonQueryAsync();
            }
         }

【讨论】:

  • System.Data.SqlClient.SqlException: 'INSERT 语句与 FOREIGN KEY 约束“FK__wallettbl__categ__75A278F5”冲突。
  • 调试并找出要插入的 categoryId 的值。它应该出现在类别表中
猜你喜欢
  • 2021-03-01
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多