C# dynamic COMBOBOX (SQL BD table data)

Asked

Viewed 15,498 times

7

I need to load a combobox with the data from an SQL DEPARTMENT table (with code and description/ the description is displayed in the combobox but what is caught is the code)

I used a datasource (the one configured automatically by clicking on the > above the combobox (graphic editing mode)).

so far perfect: It perfectly loads the data and passes the code but here comes my problem: My application is composed of a form divided into two (split.panel) on one side has navigation and on the other side some panels overlapped one for each type of registration etc... One of these panels is the DEPARTMENT register, when I register a department and I go to the other panel where has this combobox this new department that I registered does not appear... Only those already registered before I open the application appear. If I close my application and open again from there appears everything.

What I have been researching the datasource does not have what I need (it is 'static'). Is there another way to do this? You don’t even have to post me all the code if you don’t want to (I can’t show you my code already done because I’m at work), you can tell me only the resources I should use or a generic example.

I tried using Combobox.Refresh(); but it didn’t help at all.

Grateful ^^

3 answers

7


You can add the code you use to register a new department within a catch Try, if no error occurs you can add the saved item in the combobox.

try
{
    Departamento departamento = new Departamento() { ID = 1, Nome = "Departamento" };
    //salvar departamento

    this.comboBox.Items.Add(departamento);
}
catch (Exception)
{
    throw;
}

Another solution is to use the method Clear() before filling out the combobox with the data, this way all items will be removed;

this.comboBox.Items.Clear();
this.comboBox.DataSource = list;
  • Thanks for the answer but I wanted something "no Ambi", say I resolve to increment this program and put the functionality to delete records?! How will I update the combobox? Will I have to add the Item.Remove (I don’t know the command) and if there are two modules (which are): one more web? Two people (at least) inserted and removing... This solution is not suitable... I need something that looks DIRECTLY FROM THE BANK and 'real-time' (at least the most current until the combobox is generated)!

  • Okay, that’s not "Ambi". You could create method that receives a delegate to inform the method that must be executed after deleting/saving a department. in this case, the method would be the same as filling the combobox with the database data.

  • 1

    It is much more natural and simply consult in the database and fill in Combobox with this data, keep adding lines and deleted each time some department is inserted/deleted is not a very 'natural' reasoning. And I wasn’t kidding when I said gambiarra :) I think I even found the solution, I will be and if it works put here for the rest of the staff. If you have any other suggestions, thank you ^^

  • the list of elements has the Clear() method, you can use this before filling the entire datasource. this way it will always remove and add everything from the bank.

  • Wow!!! I will test this for sure. Put this comment as a response ^^

  • I added in the description of the same answer, since they are two possible solutions :)

Show 1 more comment

3

If someone has this same doubt, follow the function I made to load the combobox:

private void preencherCBDescricao()
        {
            String scon = "Data Source=NOME DO SERVIDOR\\BASESQL;Initial Catalog=SI_ATPS;Persist Security Info=True;User ID=sa;Password=MINHASENHA";
            con = new SqlConnection(scon);
            try
            {
                con.Open();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
            }
            String scom = "select * from departamento";
            SqlDataAdapter da = new SqlDataAdapter(scom,con); 
            DataTable dtResultado = new DataTable();
            dtResultado.Clear();//o ponto mais importante (limpa a table antes de preenche-la)
            comboBox1.DataSource = null;
            da.Fill(dtResultado);
            comboBox1.DataSource = dtResultado;
            comboBox1.ValueMember = "codigo";
            comboBox1.DisplayMember = "descricao";
            comboBox1.SelectedItem = "";
            comboBox1.Refresh(); //faz uma nova busca no BD para preencher os valores da cb de departamentos.
    }
  • Hi, Mariana, to communicate we use the comments, questions and answers should focus on the technical part. You can mark Italo’s response as correct, check out How and why to accept an answer?

  • Thanks, I’m new and I didn’t know! I’ll take care of it.

1

Good night, I was going through a problem like this in my academic project, with the answers of chi and li I managed to do what I really wanted.

Using C# with Sqlserver

The project is in POO, then follows the class and buttons

    // aqui é o Evento do botão Clicar do comboBox
    private void cmbCategoria_Click(object sender, EventArgs e)

    {

        CategoriaNegocio catNegocio = new CategoriaNegocio();
        List<Categoria> categoria = catNegocio.ListarCategoriasCombo();

        /* 
          OBS: NA PROPRIEDADE cmbCategoria DataBindings o Text tem que estar (none)
          DataSource (o que vai ser carregado) --> Aqui esta pegando a Lista de categorias, preenchidas 
          com o select do  método ListarCategoriasCombo
          DisplayMember = "nomeCategoria" -->  o campo que vai carregar da tablea (exibir no combo) tem que ser igual ao do SQL
          cmbCategoria.ValueMember --> o valor que vai retornar pra programacao
          SelectedValue = "idProduto"  --> gravar na FK da tabela Produto, e passa para o produto (inserir)           
         */

        this.cmbCategoria.DataSource = categoria;
        this.cmbCategoria.DisplayMember = "nomeCategoria";
        this.cmbCategoria.ValueMember = "idCategoria";
        this.cmbCategoria.SelectedValue = "idProduto";

    }



   // metodo que retorna uma lista de categorias do SQL com uma "tabela" usando o filtro        
    public List<Categoria> ListarCategoriasCombo()
    {

       // select que vai ao banco e retorna a consulta já ordenada
        string _SQL = @"select 
                        idCategoria,nomeCategoria
                        from Categoria
                        order by nomeCategoria";
        //mandar instrucoes ao sql  (Command)
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = clsConexao.Conectar();
        cmd.CommandText = _SQL;
        SqlDataReader dr = cmd.ExecuteReader();
        List<Categoria> categorias = new List<Categoria>();
        // quando acabar as linhas que retornou da consulta, sai do While
        while (dr.Read())
        {
            Categoria cat = new Categoria();
            cat.idCategoria = dr.GetInt32(dr.GetOrdinal("idCategoria"));
            cat.nomeCategoria = dr.GetString(dr.GetOrdinal("nomeCategoria"));
            categorias.Add(cat);
        }

        cmd.Connection.Close();
        cmd.Dispose();

        return categorias;

    }




  // objeto transferencia onde preencho o Objeto
  public class Categoria
  {
    public int idCategoria { get; set; } 
    public string nomeCategoria { get; set; }
    public string descCategoria { get; set; }

  }

I hope I contributed =D

Browser other questions tagged

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