Reputation: 1053
Hi I am trying to output a list of items from a table over linq to a dropdown list
I am getting an error on the linq query: Cannot implicitly convert generic.list<string> to generic.List<locations>
Can someone help please? Thanks in advance.
public static void getlocation()
{
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();
List<Location> locations = (
from a
in dc.Locations
select a.Name).ToList();
DropDownList ddLocation = new DropDownList();
locations.ToList();
ddLocation.DataSource = locations;
ddLocation.DataBind();
ddLocation.SelectedIndex = 0;
}
Upvotes: 1
Views: 1140
Reputation: 223362
You are selecting a single column select a.Name
and then you are trying to store the result of ToList
to List<Locations>
. Your current query would probably result in List<string>
which is not assignable to List<Locations>
You can fix that by selecting select a
List<Location> locations = (
from a in dc.Locations
select a).ToList();
You also don't need locations.ToList();
in your code, since locations
is already a list. That is just redundant and you are not even assigning the result of ToList
to any other field.
Edit:
You need to set DataTextField and DataValueField property of your DropDownList
as well like:
ddLocation.DataValueField = "ID"; //Whatever you need the ID to be when selected
ddlLocation.DataTextField = "Name";
If you just want to show names and your selected value would be name as well then you can do:
DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();
List<string> locations = (
from a in dc.Locations
select a.Name).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataBind();
ddLocation.SelectedIndex = 0;
Not really sure why you need to create ddlLocation
inside your code, You can create that in ASPX code and just do the binding in code behind.
Upvotes: 1