我有一个在打开主窗体时调用的方法
private void populateComboBoxes()
{
SqlCeDataAdapter breakfastAdapter = new SqlCeDataAdapter("SELECT DISTINCT recipeName FROM Recipe WHERE Category = 'breakfast' ", databaseConnection);
SqlCeDataAdapter lunchAdapter = new SqlCeDataAdapter("SELECT DISTINCT recipeName FROM Recipe WHERE Category = 'lunch' ", databaseConnection);
breakfastAdapter.Fill(breakfastDS, "Recipe");
lunchAdapter.Fill(lunchDS, "Recipe");
cmbBox1.DisplayMember = "recipeName";
cmbBox1.ValueMember = "recipeName";
cmbBox1.DataSource = breakfastDS.Tables["Recipe"];
cmbBox2.DataSource = lunchDS.Tables["Recipe"];
cmbBox2.DisplayMember = "recipeName";
cmbBox2.ValueMember = "recipeName";
}
基本上根据SELECT语句填充两个组合框。一旦此方法命中cmbBox1.DataSource = breakfastDS.Tables["Recipe"]
,它就会停止执行并转移到此方法:
private void cmbBox1_SelectedIndexChanged(object sender, EventArgs e)
{
rtbPicture.Visible = false;
string qry = "";
qry = "SELECT DISTINCT ingredientName FROM Recipe WHERE recipeName = " + cmbBox1.SelectedItem.ToString();
SqlCeCommand com = new SqlCeCommand(qry, databaseConnection);
com.CommandText = qry;
rtbRecipe.Text = com.ExecuteScalar().ToString();
}
此方法应该执行select语句并将该信息放在richtextbox
中,但由于某种原因cmbBox1
未设置。根据我的理解,第一个combobox
已经在前一个方法中设置了显示和值成员。但是,当我到达cmbBox1.SelectedItem.ToString()
时,它会返回System.Data.DataRowView
而不是combobox
中的实际字符串。我不确定为什么它会给我System.Data.DataRowView
而不是字符串。
答案 0 :(得分:3)
您正在使用cmbBox1.SelectedItem.ToString()
。
您可能应该使用SelectedValue
代替:
qry = "SELECT DISTINCT ingredientName FROM Recipe WHERE recipeName = " + cmbBox1.SelectedValue.ToString();
SelectedItem
获取实际的ComboBox
项(在本例中为DataRowView
),而SelectedValue
获取您指定为ValueMember
的属性的值ComboBox
。
答案 1 :(得分:0)
cmbBox2.DisplayMember =“recipeName”;
cmbBox2.DataSource = lunchDS.Tables [“Recipe”];
cmbBox2.ValueMember =“recipeName”;