I have one string collection and I am executing foreach loop on the string collection. So in foreach I want to bind value to dropdownlist using LINQ query. That time for loop executed without error, but binding in dropdownlist is overriding the value.
Please check my snippet:
public void binddrop(StringCollection colle)
{
foreach (string str in (StringCollection)colle)
{
string[] user = str.Split('|');
iPhoneDataContext objdata = new iPhoneDataContext();
var userdetails = (from users in objdata.UserDetails.AsEnumerable()
where users.UserType != null && users.Email==user[2].ToString()
select new
{
Name = users.FirstName,
ID = users.UserId
})
drpvendor.DataSource = userdetails;
drpvendor.DataTextField = "Name";
drpvendor.DataValueField = "ID";
drpvendor.DataBind();
}
drpvendor.Items.Insert(0, new ListItem("-Select Vendor-", "0"));
}
For some reason the for loop for StringCollection overrides the value in dropdownlist. So how could I bind in another way?
The reason that the value gets overwritten is because you are doing the binding inside the foreach. Basically on first foreach cycle you are getting first userdeails and then binding it to the DDL, on next cycle you are binding the 2nd userdetails to the DDL and so on, so what you get in the end is just the last userdetails in the DDL.
What you need to do is to get all the userdetails in a collection and then databind the DDL onto that collection.
You need to do something like this:
[Index.aspx.cs]
[Index.aspx]