我正在开发一个 C# Windows 窗体应用程序。我想在组合框中获取所选项目的 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 PartId=@PartId";
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();
}
任何帮助将非常感激。