Bind Value and Range to dropdown in C# with LINQ
Quick question. Its easy enough to bind a value and text to a drop down in markup, how can I do this in C#.
To bind a single column collection
_dd_City.DataSource = LNQ.tbl_cities.Select(a =>开发者_开发百科; a.desc);
_dd_City.DataBind();
however say I wanted to set the value to an integer value and the text to the city name, how could I do that ??
You just need to specify the name of the properties from the objects in your collection that will be used for the text and value like this:
_ddCity.DataTextField = "desc";
_ddCity.DataValueField = "Id";
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new { a.Id, a.desc});
_dd_City.DataBind();
You can set the text and value field on your markup too.
<asp:DropDownList ID="_ddCity" runat="server" DataValueField="Id" DataTextField="desc">
</asp:DropDownList>
Say your City object has members called "Id" and "CityName", you would just do this before calling DataBind:
_dd_City.DataTextField = "CityName";
_dd_City.DataValueField = "Id";
_dd_City.DataValueField="value"
_dd_City.DataTextField="key"
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new {value=a.desc, key=a.id});
_dd_City.DataBind();
精彩评论