Combobox和System.Data.DataRowView

时间:2013-03-25 21:50:54

标签: c# database sql-server-ce

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

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

2 个答案:

答案 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”;