views:

240

answers:

2

I have access to a sharepoint list like so:

SPList countries = site.RootWeb.Lists["Countries"];

the list has a CountryCode column and a CountryName column

using linq how can i databind this as a datasource for a drop down so that the "Value" is "CountryCode" and the "Text" is "CountryName"

+1  A: 

Its not needed that you need to use the LINQ here it is directly possible. Assuming that your DropDownList Name is ddl here is the code

DataTable dt = countries.Items.GetDataTable();
ddl.DataTextField="Countryame";
ddl.DataValueField="CountryCode";
ddl.DataSource=dt; 
ddl.DataBind();
Kusek
+2  A: 

If you do want to use LINQ instead of GetDataTable():

SPList list = site.RootWeb.Lists["Countries"];
var countries = from SPListItem li in list.Items
                select new {
                    CountryName = li["CountryName"],
                    CountryCode = li["CountryCode"]
                };

ddl.DataSource = countries;
ddl.DataTextField="CountryName";
ddl.DataValueField="CountryCode";
ddl.DataBind();
dahlbyk
Nice clear use of anonymous types
Alex Angas