I have a linq query that pulls down some records. It could be 1 record, 2 records or 30 records. I have two textboxes I want the records to go into if there is only 1 record or only 2 records then it if its over that it puts it in a dropdownlist. This is what I have so far.
var getContacts = (from r in gServiceContext.CreateQuery("account")
join c in gServiceContext.CreateQuery("contact") on ((EntityReference) r["accountid"]).Id
equals c["accountid"]
where r["accountid"].Equals(ddlCustomer.SelectedValue)
select new
{
FirstName = !c.Contains("firstname") ? string.Empty : c["firstname"],
LastName = !c.Contains("lastname") ? string.Empty : c["lastname"],
});
foreach (var contact in getContacts)
{
if (getContacts.ToList().Count() == 1)
{
txtContact1Name.Text = contact.FirstName + " " + contact.LastName;
}
else if (getContacts.ToList().Count() == 2)
{
txtContact2Name.Text = contact.FirstName + " " + contact.LastName;
}
else if (getContacts.ToList().Count() > 2)
{
ddlMultipleContacts.DataSource = getContacts;
ddlMultipleContacts.DataTextField = "LastName";
ddlMultipleContacts.DataValueField = "LastName";
ddlMultipleContacts.DataBind();
}
}
But it puts the same record in textbox 1 and textbox two if there are two records. Am I doing something wrong?
Thanks!
Yes. Look at your code:
You’re calling that on each iteration – you’re not using the count of how many contacts you’ve already used. I suspect you want: