all groups > asp.net webcontrols > december 2007 >
You're in the

asp.net webcontrols

group:

DropDownList Binding to LINQ DataSource


DropDownList Binding to LINQ DataSource John Padilla
12/15/2007 11:08:00 AM
asp.net webcontrols: I was playing around with the LINQtoSQL and found an interesting problem.

i am using the Northwind database on SQL 2005 Developer Server.
In my webform's PageLoad event I have the following code:

NorthwindDataContext db = new NorthwindDataContext();

var customers = from c in db.Customers
orderby c.CompanyName
select new
{
c.CompanyName,
c.CustomerID
};

ddCustomers.DataSource = customers;
ddCustomers.DataTextField = "CompanyName";
ddCustomers.DataValueField = "CustomerID";
ddCustomers.DataBind();

ddCustomers is a regular Asp.net DropDownList control.

The data populates correctly in the control at runtime. The problem occurs
when i try to select an item in the list and the control's
SelectedIntexChanged event fires .

I need the CustomerID to populate a grid from another linq query but it
doesnt matter which item in the dropdownlist i choose, once the
selectedindexevent fires the index is always set to 0 and after the postback
finishes and the page is re-rendered the dropdownlist again shows the first
Customer inthe list (index = 0)

Note when I use the LinqDataSource control in replace of my page load query
Re: DropDownList Binding to LINQ DataSource David R. Longnecker
12/19/2007 2:57:34 PM
John-

Would it be beneficial to surround your data fetching code in Page_Load()
with:

if (!Page.IsPostback)
{

// code

}

Your code is refetching and rebinding your data each time--to the default
values. Page_Load fires on each postback so, when your SelectedIndexChanged
fires and the page posts back, the data source resets. :)

HTH.

-dl

--
David R. Longnecker
http://blog.tiredstudent.com

[quoted text, click to view]

AddThis Social Bookmark Button