Search code examples
c#comboboxsqlconnectionsqldataadapter

How do I sync data from a database to a combobox


I'm creating a form of which I have to show the data from a database into a combo box and I need help to do it, please

I have already tried to download MySql Server, however, it only supports up to Visual Studio 2017 and I have 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!");
    }
}

I would have expected the data from the database however, I got an output of nothing


Solution

    1. Set comboBox3.ValueMember="USERNAME" and comboBox3.DisplayMember="USERNAME" , Use "USERNAME", not "Userame", because your sql is select USERNAME
    2. Check if ds.Tables["Username"].Rows.Count>0