1

我有一个在打开主窗体时调用的方法

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而不是字符串。

4

2 回答 2

3

您正在使用cmbBox1.SelectedItem.ToString(). 您可能应该SelectedValue改用:

qry = "SELECT DISTINCT ingredientName FROM Recipe WHERE recipeName = " + cmbBox1.SelectedValue.ToString();

SelectedItem获取实际ComboBox项目(在本例中为 a DataRowView),而SelectedValue获取您指定为 的属性的ValueMemberComboBox

于 2013-03-25T21:55:37.350 回答
0

cmbBox2.DisplayMember = "配方名称";

cmbBox2.DataSource = lunchDS.Tables["食谱"];

cmbBox2.ValueMember = "配方名称";

于 2013-09-28T13:18:14.843 回答