Combobox and System.Data.DataRowView

狂风中的少年 提交于 2019-12-13 02:25:32

问题


I have a method that is called when the main form is opened

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";                      
}

which essentially populates the two comboboxes based on the SELECT statements. Once this method hits cmbBox1.DataSource = breakfastDS.Tables["Recipe"] it stops executing and moves to this method:

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();
}

This method is supposed to execute the select statement and put that information in the richtextbox, but for some reason cmbBox1 isn't set. From my understanding the first combobox already had set the display and value members in the previous method. However, when I get to the cmbBox1.SelectedItem.ToString() it returns System.Data.DataRowView instead of the actual string in the combobox. I'm not sure why it's giving me System.Data.DataRowView instead of the string.


回答1:


You are using cmbBox1.SelectedItem.ToString(). You should probably be using SelectedValue instead:

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

SelectedItem gets the actual ComboBox item (in this case a DataRowView), whereas SelectedValue gets the value of the property you specified as the ValueMember of the ComboBox.




回答2:


cmbBox2.DisplayMember = "recipeName";

cmbBox2.DataSource = lunchDS.Tables["Recipe"];

cmbBox2.ValueMember = "recipeName";



来源:https://stackoverflow.com/questions/15625479/combobox-and-system-data-datarowview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!