Two dependent combobox using Linq to sql

Asked

Viewed 301 times

5

How do I fill 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 how I filled one, if there is any error and want to give some suggestion I thank you very much. Thank you all :)

Assim Foi como preenchi uma combobox

  • One important thing: don’t post a screenshot of the code, the code itself (and well formatted) is much easier to read, not to mention that there are people who use the site and have some kind of lock (as you can see the images are in another domain).

1 answer

2


A few points before solving the problem.

  1. Your premise on how to fill the combo is not wrong, but it’s not the best way to do it. It is not necessary to iterate the items and add them one by one, it is possible to use a collection as DataSource combobox.

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

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

Anyway, to solve your problem, you will need to use the event SelectedValueChanged Combobox (it can be anyone who fires when changing the selected item, I prefer this).

Example of what your code would look like (the example uses countries, states and cities, but the 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();
    }
}

Browser other questions tagged

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