如何将数据从数据库同步到组合框

时间:2019-06-19 20:15:00

标签: c# combobox sqlconnection sqldataadapter

我正在创建一种表格,必须将数据库中的数据显示到组合框中,需要我的帮助

我已经尝试下载MySql Server,但是,它最多仅支持Visual Studio 2017,并且我具有Visual Studio 2019

using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Code\C#\MyFirstUI\MyFirstUI\LOGIN.mdf;Integrated Security=True"))
{
    try
    {
        string query = "select USERNAME from LOGIN";
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        conn.Open();
        DataSet ds = new DataSet();
        da.Fill(ds, "Username");
        comboBox3.DisplayMember = "Userame";
        comboBox3.DataSource = ds.Tables["Username"];
    }
    catch (Exception ex)
    {
        // write exception info to log or anything else
        MessageBox.Show(ex.Message,"Error occured!");
    }
}

我本来希望从数据库中获得数据,但是我什么也没得到

1 个答案:

答案 0 :(得分:0)

  1. 设置comboBox3.ValueMember="USERNAME"comboBox3.DisplayMember="USERNAME",使用“ USERNAME”而不是“ Userame”,因为您的SQL是select USERNAME
  2. 检查是否ds.Tables["Username"].Rows.Count>0