ComboBox无法显示新增值

时间:2013-12-05 15:46:07

标签: c# wpf

我在我的组合框中添加了一个新值,它应该根据我在数据库中的内容显示。但遗憾的是,新值并未显示出来。以下是我的代码。

string dbConn = "Data     Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYearProject\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";

void fill_Combo() { 
       SqlConnection conn = new SqlConnection(dbConn);
       try {
           conn.Open();
           string query = "Select * From Food";
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read()) {
                string name = dr.GetString(1);
                comboBox1.Items.Add(name);
            }
            conn.Close();
       }
       catch(Exception ex){
           MessageBox.Show(ex.Message);
       }
    }

2 个答案:

答案 0 :(得分:0)

您应该使用可观察集合作为数据源并绑定到该集合。见Add items to comboBox in WPF

答案 1 :(得分:0)

嗨,请尝试这样的事情,希望有所帮助

string dbConn = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\SONY\\Desktop\\FinalYearProject\\FinalYear Project\\bin\\Debug\\housewife.mdf;Integrated Security=True;User Instance=True";

void fill_Combo() { 
   SqlConnection conn = new SqlConnection(dbConn);
   try {
       conn.Open();
       string query = "Select * From Food";
        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds)
        combobox1.DataSourse = ds;
        combobox1.DisplayMember = "fieldname";
        combobox1.ValueMember = "fieldname";
   }
   catch(Exception ex){
       MessageBox.Show(ex.Message);
   }
}