A few points before solving the problem.
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.
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).
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();
}
}
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).
– Jéf Bueno