COMBOBOX dynamically in C # (SQL DB table data)

3

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

I used a dataSource (the one automatically configured by clicking on> on top of the combobox (graphical editing mode)).

So perfect: Load perfectly the data and pass the code right 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 some overlapping one panels for each type of cadastre etc ... One of these panels is the registration of DEPARTMENT, when registering a department and I go to the other panel where there is 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 it again then everything appears.

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

I tried using Combobox.Refresh (); but it did not help.

Thanks ^^

    
asked by anonymous 03.11.2014 / 14:50

3 answers

2

You can add the code you use to register a new department within a try catch, if there is no error 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 Clear() method before filling the combobox with the data, so all items will be removed;

this.comboBox.Items.Clear();
this.comboBox.DataSource = list;
    
03.11.2014 / 18:43
1

If someone has the same question, follow the function I did 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.
    }
    
03.11.2014 / 22:15
0

Good evening, I was going through such a problem in my academic project, with the answers from Chi and I got to do what I really wanted.

Using C # with SQLServer

The project is in OOP, so follow 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

    
14.05.2017 / 00:28