C# 如何将 LINQ 数据绑定到下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:59:34 来源:igfitidea点击:
How to bind LINQ data to dropdownlist
提问by alchemical
The last two lines of this code do not work correctly -- the results are coming back from the LINQ query. I'm just not sure how to successfully bind the indicated columns in the results to the textfield and valuefield of the dropdownlist:
这段代码的最后两行不能正常工作——结果是从 LINQ 查询返回的。我只是不确定如何将结果中指示的列成功绑定到下拉列表的文本字段和值字段:
protected void BindMarketCodes()
{
List<lkpMarketCode> mcodesList = new List<lkpMarketCode>();
LINQOmniDataContext db = new LINQOmniDataContext();
var mcodes = from p in db.lkpMarketCodes
orderby 0
select p;
mcodesList = mcodes.ToList<lkpMarketCode>();
//bind to Country COde droplist
dd2.DataSource = mcodesList;
dd2.DataTextField = mcodesList[0].marketName;
dd2.DataValueField = mcodesList[0].marketCodeID.ToString();
}
采纳答案by James
See revised code below
请参阅下面的修订代码
protected void BindMarketCodes()
{
using (var dataContext = new LINQOmniDataContext()) {
//bind to Country COde droplist
dd2.DataSource = from p in dataContext.lkpMarketCodes
orderby p.marketName
select new {p.marketCodeID, p.marketName};
dd2.DataTextField = "marketName";
dd2.DataValueField = "marketCodeID";
dd2.DataBind();
}
}
回答by andleer
protected void BindMarketCodes()
{
using(var dc = new LINQOmniDataContext())
{
dd2.DataSource = from p in db.lkpMarketCodes
orderby 0
select new {p.marketName, p.marketCodeID };
dd2.DataTextField = "marketName";
dd2.DataValueField = "marketCodeID";
dd2.DataBind();
}
}
// no need to use ToList()
// no need to use a temp list;
// using an anonymous type will limit the columns in your resulting SQL select
// make sure to wrap in a using block;
回答by Siddhartha Sengupta
DropDownList ddl_RouteLocation = (DropDownList)e.Row.FindControl("ddl_RouteLocation");
ddl_RouteLocation.DataSource = dtLocation;--(dtlocation i have return method of linq in dtlocation)
ddl_RouteLocation.DataTextField =dtLocation.Rows[0]"LocationName"].ToString();
ddl_RouteLocation.DataValueField =dtLocation.Rows[0]["LocationId"].ToString();
ddl_RouteLocation.DataBind();
ddl_RouteLocation.Items.Insert(0, new ListItem("--Select--", "0"));