Reputation: 11
I have a simple question that is driving me mad. I am trying to query a data entity and everything works until I try to reference something external. In the code below (which works perfectly) I want to change the .where clientID == 15 to .where the client ID is the value shown in a combobox, the combobox valuemember is an integer:
private void cboxcos_SelectionChangeCommitted(object sender, EventArgs e)
{
using (var context2 = new tvdm())
{
var cus = context2.tblContacts
.Where(c => c.ClientID == 15)
.Select(c => new {c.LastName, c.FirstName, c.JobTitle, c.Telephone, c.Mobile, c.EMail })
.OrderBy(p => p.LastName)
.ToList();
dataGridView1.DataSource = cus;
}
}
Any simple help would be greatly appreciated.
I am using VS2015 Community with C# and EF6
Upvotes: 1
Views: 83
Reputation: 11
I actually ended up with:
private void cboxcos_SelectionChangeCommitted(object sender, EventArgs e)
{
using (var context2 = new tvdm())
{
int value = (int)cboxcos.SelectedValue;
var cus = context2.tblContacts
.Where(c => c.ClientID == value)
.Select(c => new {c.LastName, c.FirstName, c.JobTitle, c.Telephone, c.Mobile, c.EMail })
.OrderBy(p => p.LastName)
.ToList();
dataGridView1.DataSource = cus;
}
}
Upvotes: 0
Reputation: 547
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
ComboBox senderComboBox = (ComboBox) sender;
int selectedValue = (int)senderComboBox.SelectedValue;
// and assuming that there's nothing wrong with this code
using (var context2 = new tvdm())
{
var cus = context2.tblContacts
.Where(c => c.ClientID == selectedValue)
.Select(c => new { c.LastName, c.FirstName, c.JobTitle, c.Telephone, c.Mobile, c.EMail })
.OrderBy(p => p.LastName)
.ToList();
dataGridView1.DataSource = cus;
}
}
Upvotes: 0
Reputation: 3702
Get the value first, cast it to the correct type and then use that parameter in the linq query:
private void cboxcos_SelectionChangeCommitted(object sender, EventArgs e)
{
int value = (int)comboBox1.SelectedValue;
using (var context2 = new tvdm())
{
var cus = context2.tblContacts
.Where(c => c.ClientID == value)
.Select(c => new { c.LastName, c.FirstName, c.JobTitle, c.Telephone, c.Mobile, c.EMail })
.OrderBy(p => p.LastName)
.ToList();
dataGridView1.DataSource = cus;
}
}
Upvotes: 5
Reputation: 37000
I suppose you need something like
var cus = context2.tblContacts
.Where(c => c.ClientID == Convert.ToInt32(myComboBox.SelectedItem))
.Select(c => new {c.LastName, c.FirstName, c.JobTitle, c.Telephone, c.Mobile, c.EMail })
.OrderBy(p => p.LastName)
.ToList();
Upvotes: 0