How to fill out combobox with SQL query? C#

Asked

Viewed 226 times

0

I wonder if it is possible to pass data from an SQL query to a combobox using C#. I researched the subject and found examples, but when I adapted to my case , I could not use. I am doing this way:

private void carregacombo()
{
    Conexao conexão = new Conexao();
    try
    {
        conexão.conectar();
        OleDbCommand cmd = new OleDbCommand("select nomeEquipe from Equipe",conexão.cn);
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataTable dtMensagens = new DataTable();
        da.Fill(dtMensagens);
        this.cmbEquipe.DataSource = dtMensagens;
        this.cmbEquipe.DisplayMember = "nomeEquipe";

    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        conexão.desconectar();
    }
}
  • Hi @Felipe. What’s the matter? A ComboBox doesn’t get filled in? You have to go into more detail about your problem.

1 answer

0

I found my error, the query should be in Oledbdataadapter and the Oledbcommand line does not exist. In the end the code was this way:

private void carregacombo()
    {
        Conexao conexão = new Conexao();
        try
        {
            conexão.conectar();
            OleDbDataAdapter da = new OleDbDataAdapter("select idEquipe,nomeEquipe from Equipe", conexão.cn);
            DataTable dtMensagens = new DataTable();
            da.Fill(dtMensagens);
            this.cmbEquipe.DataSource = dtMensagens;
            this.cmbEquipe.ValueMember = "idEquipe";
            this.cmbEquipe.DisplayMember = "nomeEquipe";

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            conexão.desconectar();
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.