插入comboBox值

时间:2017-04-02 16:20:25

标签: sql winforms combobox insert

我尝试在表中插入comboBox值,我试试这个

public void additem(string name,int cost,int f)
    {
        con.Open();
        cmd = new SqlCommand("insert into Item(ItemName,ItemCost,ItemCategoryIdF)values(@ItemName,@ItemCost,@ItemCategoryIdF)", con);
        cmd.Parameters.AddWithValue("@ItemName", name);
        cmd.Parameters.AddWithValue("@ItemCost", cost);
        cmd.Parameters.AddWithValue("@ItemCategoryIdF", f);
        cmd.ExecuteNonQuery();
    }

并点击按钮

  private void button1_Click(object sender, EventArgs e)
    {
        con.Open();
        string name = textBox1.Text;
        int cost = Convert.ToInt32(textBox2.Text);
        int f = Convert.ToInt32(comboBox1.Selectedvalue);
        Items ab = new Items();
        ab.additem(name, cost, f);
        cmd.ExecuteNonQuery();
        MessageBox.Show("Item Is Inserted!");
        con.Close();
    }

这个插入成功但是当我在表中检查时f值显示0和0值插入表中..那么我如何从comboBox1in表中插入所选值?

当我从组合框中选择值然后该值应该在f ..假设在组合框中值是芯片,糖果,饼干所以如果我选择饼干那么f值应该是b 2因为芯片为1,糖果为2,饼干为3

更新了代码但显示错误

**Additional information: Cannot bind to the new display member.**

值我在comboxbox中加载

 private void Item_Load(object sender, EventArgs e)
    {
        Global.objCon = new SqlConnection(Global.con);      
        Global.sqlquery=("select CategoryId,CategoryName from Category");
        Global.objCon.Open();
        Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
        Global. dr = Global.objcmd.ExecuteReader();
        ArrayList arr = new ArrayList();
        while(Global.dr.Read())
        {
            AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
            arr.Add(obj);
        }
        reader.Close();
        Global.objCon.Close();
        comboBox1.DataSource = arr;
        comboBox1.DisplayMember = "CategoryName";
        comboBox1.ValueMember = "Categoryid";


    }

任何帮助

1 个答案:

答案 0 :(得分:0)

试试这个:

 private void Item_Load(object sender, EventArgs e)
{
    Global.objCon = new SqlConnection(Global.con);      
    Global.sqlquery=("select CategoryId,CategoryName from Category");
    Global.objCon.Open();
    Global.objcmd = new SqlCommand(Global.sqlquery, Global.objCon);
    Global. dr = Global.objcmd.ExecuteReader();
    BindingList<AddItem> arr = new BindingList<AddItem>();
    while(Global.dr.Read())
    {
        AddItem obj=new AddItem(Convert.ToInt16(Global.dr["CategoryId"]),Global.dr["CategoryName"].ToString());
        arr.Add(obj);
    }
    reader.Close();
    Global.objCon.Close();
    comboBox1.DataSource = arr;
    comboBox1.DisplayMember = "CategoryName";
    comboBox1.ValueMember = "Categoryid";
}