我有一个在打开主窗体时调用的方法
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
已经在前面的方法中设置了display和value成员。但是,当我到达cmbBox1.SelectedItem.ToString()
时,它返回System.Data.DataRowView
而不是combobox
中的实际字符串。我不知道为什么它给我System.Data.DataRowView
而不是字符串。 最佳答案
您正在使用cmbBox1.SelectedItem.ToString()
。
您可能应该改用SelectedValue
:
qry = "SELECT DISTINCT ingredientName FROM Recipe WHERE recipeName = " + cmbBox1.SelectedValue.ToString();
SelectedItem
获取实际的ComboBox
项(在本例中为aDataRowView
),而SelectedValue
获取指定为ValueMember
的ComboBox
属性的值。关于c# - 组合框和System.Data.DataRowView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15625479/