Two dependent combobox using linq to sql

5

How do I populate two combobox's with linq to sql where in a combobox for example I have countries and in another I have cities? How do they automatically change the values? I leave the image below as I filled out one, if there are any errors and want to give some suggestion thank you very much. Thank you all :)

    
asked by anonymous 06.05.2016 / 02:16

1 answer

2

Some points before solving the problem.

  • Your premise of filling in the combo is not wrong, but it is not the best way to do it. It is not necessary to iterate the items and add them one by one, you can use a collection like DataSource of the ComboBox.

  • You are only adding the name of the items in the ComboBox, this is wrong (back to the above case, use the DataSource property and populate the ComboBox with a list of objects). >

  • Always give Dispose in the context after doing some operation with the database, even without having the rest of the code, it seems to me that this is not being done. (In my code this is done with using , you can see more about it "> here .

  • Finally, to solve your problem, you will need to use the SelectedValueChanged event of the ComboBox (it can be anyone who triggers when changing the selected item, I prefer this).

    Example of how your code would look (example uses countries, states, and cities, but logic is the same):

    public Form1()
    {
        InitializeComponent();
    
        cbPais.DisplayMember = 
        cbEstado.DisplayMember = 
        cbCidade.DisplayMember = "Nome";
        //Define qual propriedade dos objetos serão mostradas no combo
    
        cbPais.ValueMember =
        cbEstado.ValueMember =
        cbCidade.ValueMember = "Id";
        //Define qual propriedade vai funcionar como valor do item selecionado
    
        using (var db = new MyContext())
        {
            cbPais.DataSource = db.Paises.ToList();
        }
    }
    
    private void cbPais_SelectedValueChanged(object sender, EventArgs e)
    {
        var paisId = Convert.ToInt32(cbPais.SelectedValue); 
        //Pega o ValueMember do item selecionado
    
        using (var db = new MyContext())
        {
            cbEstado.DataSource = db.Estados.Where(x => x.PaisId == paisId).ToList();
        }
    }
    
    private void cbEstado_SelectedValueChanged(object sender, EventArgs e)
    {
        var estadoId = Convert.ToInt32(cbEstado.SelectedValue);
        using (var db = new MyContext())
        {
            cbCidade.DataSource = db.Cidades.Where(c => c.EstadoId == estadoId).ToList();
        }
    }
    
        
    08.05.2016 / 20:04