Reputation: 150
I have a ComboBox
of provinces :
public Form1()
{
InitializeComponent();
using (AbEntities c = new AbEntities())
{
comboBox1.DataSource = c.tbl_Province.ToList();
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "Province";
}
}
Now I want to list cities for each province in another combobox.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString() != null)
{
int pvc = Convert.ToInt32(comboBox1.SelectedValue.ToString());
string sqlString = "SELECT ID,City FROM tbl_City Where ProvinceID = pvc"
using (AbEntities c = new AbEntities())
{
comboBox2.DataSource = c.tbl_City.ToList();
comboBox2.ValueMember = "ID";
comboBox2.DisplayMember = "City";
}
}
}
I wrote the following query. But cities are not filtered
Upvotes: 1
Views: 135
Reputation: 23732
I don't see any filtering in your code. May be you should apply some like this:
comboBox2.DataSource = c.tbl_City.Where(x=>x.ProvinceID == pvc).ToList();
Explanation:
The loose SQL-query string in your code has no application. Since your post is tagged with entity-framework
I assume that AbEntities
is a DataContext
.
In this case tbl_City
implements the IQueryable
interface and allows you to call Where
directly in your code. In this example I used the method syntax.
The ToList()
call will execute the query and materialize the results.
This can also be accomplished using the query syntax:
comboBox2.DataSource = (from x in c.tbl_City
where x.ProvinceID == pvc
select x).ToList();
Upvotes: 1
Reputation: 17658
You need to query your DbSet, e.g.:
c.tbl_City.Where(c => c.ProvinceID == pvc).ToList();
Further:
there is no relation between the SQL statement and the filter.
You might want to read something about linq,
And here is more about EF: http://www.entityframeworktutorial.net/querying-entity-graph-in-entity-framework.aspx
Upvotes: 1