首页 > 解决方案 > 将 varchar 值“cat_id”转换为数据类型 int 时转换失败

问题描述

如何将cateogry_id从另一个表加载并保存到组合框中,但在组合框中显示Cateogry_Name c#?我的保存代码:

    con.Open();
    comboBox1.Text.ToString();
    String Query = "INSERT INTO tbl_Item (Cat_id, Barcode, ItemName, Unit, Quantity, SalePrice, PPrice) VALUES ('"+ comboBox1.ValueMember + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "')";

    SqlDataAdapter SDA = new SqlDataAdapter(Query, con);
    SDA.SelectCommand.ExecuteNonQuery();
    float mg = float.Parse(textBox6.Text) - float.Parse(textBox7.Text);
    label10.Text = mg.ToString();

    con.Close();            

    MessageBox.Show("Data Saved!");
}
catch (Exception ex)
{
        MessageBox.Show(ex.Message);
}
con.Close();    

也是一种方法

protected void FillCombo()
{
    DataSet ds = new DataSet();

    try
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tbl_cateogry", con);
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        da.Fill(ds);
        comboBox1.DisplayMember = "Cat_Name";
        comboBox1.ValueMember ="Cat_id";
        comboBox1.DataSource = ds.Tables[0];

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    con.Close();
}

当我运行它时,它告诉我“将 varchar 值“cat_id”转换为数据类型 int 时转换失败”请发布写入代码

标签: c#

解决方案


在我看来,您正在尝试将空字符串“”传递给它应该是 int 的地方。

您的 Cat_id 是否设置为自动增量?如果是,只需跳过 Cat_id 并仅传递其他值。


推荐阅读