2017-04-02 62 views
0

我嘗試在表中插入組合框的值爲了這個,我試試這個插入組合框的值

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.** 

值I 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"; 


    } 

任何幫助加載

+0

什麼f的原值?並且無需打開sql連接並在您的按鈕單擊事件中再次調用ExecuteNonQuery,而您已在addItem方法中執行此操作。 –

+0

f值是來自組合框,並確定我評論,執行非查詢 – scorpio

+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"; 
} 
+0

沒有。我不想選擇索引,因爲這從0開始,而在數據庫表中的值是從1而不是從0,所以當我選擇餅乾值應該是3 .. – scorpio

+0

,因爲combobox值填充數據庫 – scorpio

+0

和抱歉我的壞我告訴你的值是從0,但我不想這 – scorpio