简体   繁体   中英

My combobox doesn't show data from database

my combo box needs to show data from my database but it shows empty. here you have my code that i'm working on, visual studio dont show any error, but combobox shows empty, any tips ?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        {
            SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
            try
            {
                cn.Open();
                string query = "select * from fornecedor where nomefornecedor='" + comboBox1 + "'";
                SqlCommand createCommand = new SqlCommand(query, cn);
                SqlDataReader dr = createCommand.ExecuteReader();
                cn.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

ExecuteReader will return a reader which you then have to use to read back your results row by row, and populate your combo box accordingly. For example, if you have a (non nullable) string column named "MyItem" in your fornecedor table, you would write something like this:

using (SqlDataReader dr = createCommand.ExecuteReader())
{
  int myItemOrdinal = dr.GetOrdinal("MyItem");
  List<object> comboBoxRows = new List<object>();
  while (dr.Read())
  {         
    string myItem = dr.GetString(myItemOrdinal);
    comboBoxRows.Add(myItem);
  }
}
comboBox1.BeginInvoke(() => comboBox1.Items.AddRange(comboBoxRows.ToArray()));

The last row populates the combo box on the UI thread, assuming reading the rows from the database is done on another thread (which is something you'd want to do to keep your UI responsive).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM