简体   繁体   中英

Linq query table column list

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM