2012-07-29 91 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设置为各自的列。