19

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:

    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();

    }
bdukes
  • 152,002
  • 23
  • 148
  • 175
alchemical
  • 13,559
  • 23
  • 83
  • 110

3 Answers3

33
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;
andleer
  • 22,388
  • 8
  • 62
  • 82
29

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();
    }
}
Chase
  • 9,289
  • 5
  • 51
  • 77
James
  • 12,636
  • 12
  • 67
  • 104
-3
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"));