2012-07-29 90 views
0

我正在研究C#窗體窗體應用程序。我想要在組合框中獲取所選項目的ID。下面是我的代碼。從Combobox窗口獲取所選項目的ID

private void ProductForm_Shown(object sender, EventArgs e) 
    { 
     SqlCeConnection Connection = new SqlCeConnection(ConString); 
     Connection.Open(); 
     SqlCeDataAdapter da = new SqlCeDataAdapter("Select * from CastingMaterial", Connection); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
     for (int i = 0; i < dt.Rows.Count; i++) 
     { 
      ProductsComboBox.Items.Add(dt.Rows[i]["PartName"]); 

     } 
     ProductsComboBox.DisplayMember = "PartName"; 
     ProductsComboBox.ValueMember = "PartId"; 
     Connection.Close(); 
    } 

    private void ProductsComboBox_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     int ProductIndex = ProductsComboBox.SelectedIndex; 
     string productName = ProductsComboBox.Text.ToString(); 
     int ProductId =Convert.ToInt32(ProductsComboBox.SelectedValue); 
     SqlCeConnection Connection = new SqlCeConnection(ConString); 
     Connection.Open(); 
     String Query = "SELECT * From CastingMaterial where [email protected]"; 
     SqlCeDataAdapter da = new SqlCeDataAdapter(Query, Connection); 
     da.SelectCommand.Parameters.AddWithValue("PartId", ProductId); 
     DataSet ds = new DataSet(); 
     SqlCeCommandBuilder commandBuilder = new SqlCeCommandBuilder(da); 

     BindingSource bsource = new BindingSource(); 

     da.Fill(ds, "CastingMaterial"); 
     bsource.DataSource = ds.Tables["CastingMaterial"]; 
     Productgv.DataSource = bsource; 
     Connection.Close(); 
    } 

任何幫助將非常感激。

回答

0

您應該將項目添加爲DataRows。相反,你是從一列中提取值:

ProductCombo.Items.Add(dt.Rows[i]); 

然後,設置將DisplayMember和ValueMember正確的,但是,因爲添加內容正確這沒有任何影響。

0

坦率地說,您需要更清楚地發佈問題。

您希望如何獲得組合框的選定ID?
你打算使用該ID的目的是什麼?

我想你應該在這裏更清楚地描述你的實際問題。 原因,代碼似乎爲我工作正常。

而且,順便說一句,你實際上並不需要一個循環來設置組合框的數據項。您只需將組合的DataSource屬性分配給剛剛提取數據的DataTable。

ProductsComboBox.DataSource = dt ...工作得很好,你知道!
然後,您可以將DisplayMemberValueMember設置爲各自的列。