Reputation:
I'm trying to use LINQ and so I can bind it to an ASP.NET dropdown.
So far; this is what I have in terms of my LINQ expression; I'm new to LINQ, I started learning it this morning.
county.DataSource = (from taxUnit in TaxUnits.Descendants("CodeData")
join taxType in TaxTypes.Descendants("CodeData")
on
taxUnit.Attribute("taxuntype").Value
equals
taxType.Attribute("codeid").Value
where taxType.Attribute("taxuntypky").Value == "CO"
select new
{
County = taxUnit.Attribute("desc"),
CodeID = taxUnit.Attribute("codeid")
});
county.DataTextField = "desc";
county.DataValueField = "codeid";
county.DataBind();
Originally I was trying to convert it into a datatable; I've been informed you can actually do direct LINQ to DropDownList binding.
<asp:Label AssociatedControlID="county" runat="server">County</asp:Label>
<asp:DropDownList
ID="county"
runat="server" />
So far the result is... when I look at the dropdown box. Based on what I'm getting from LINQPad I expect
County CodeID
Willow County 1
CP2 TU 2
The only problem with the current answer is I have no idea how it works, thus I do not understand how to convert it to what I want.
I was previously able to use an ObjectDataSource that pointed to this method, and made a mock for List just to play with databinding.
Upvotes: 3
Views: 496
Reputation: 100288
If the actual question is - how to bind LINQ to XML result onto a DropDownList then here's a code from my old ASP.NET project. I bind LINQ to Entities result onto GridView. For DropDownList should work same way:
public IEnumerable<IDraft> Get(int accountId, DateTime startDate, DateTime endDate)
{
using (var db = new ModelContainer())
{
var account = db.Accounts.SingleOrDefault(a => a.ID == accountId);
return (from d in account.Drafts
let date = d.Date.Date
where startDate.Date <= date && date <= endDate.Date
orderby d.Date ascending
select d).ToArray();
}
}
protected void gridView_OnDataBinding(object sender, EventArgs e)
{
((IDataBoundControl)sender).DataSource = IoC.Resolve<IOperationRepository>().GetShared(this.ObjectId.Value, ucChooseDate.StartDate, ucChooseDate.EndDate);
}
Upvotes: 1