Sunday, January 25, 2009

A Short Example for LinqDataSource Control

Suppose that you want to fill a DropDownList with the list of products using a LinqDataSource control and then select a product with minimum unit price as the default value for the DropDownList.

1. Add a LINQ to SQL Class to your ASP.NET project (default name might be DataClasses.dbml).


2. Add tables that you need for your project (including the table for products that might be called Products as in the Microsoft Northwind database).


3. Declare a LinqDataSource control:

LinqDataSource lds = new LinqDataSource();


4. Set its ContextTypeName and TableName:


lds.ContextTypeName = "NWDataClassesDataContext";
lds.TableName = "Products";

The LinqDataSource control is ready be used!


5. Set data properties for your DropDownList:


DropDownList1.DataSource = lds;
DropDownList1.DataValueField = "ProductID";
DropDownList1.DataTextField ="ProductName";
DropDownList1.DataBind();


Now, your DropDownList is working.


6. Select a product with the minimum unit price as the default value selected in the DropDownList control:


DataClassesDataContext dc = new DataClassesDataContext();
decimal? minUnitPrice = (decimal?)(from p in dc.Products select p.UnitPrice).Min().Value;
var q = from p in dc.Products where p.UnitPrice == minUnitPrice select p.ProductID;
DropDownList1.SelectedValue = q.Min().ToString();


Run your project and see the result!

1 comment: