/*______________________________________________________________ * G E T T I N G T O K N O W L I N Q Step 3 * * C# VERSION * Ron Kessler * 2/5/09 * * * _____________________________________________________________ */ // This time lets us choose a category from a drop down listbox. //I show how to use an Alias in the Linq Query and how to format data as currency. //Look at the properties for the grid. I right-aligned the columns and used a Verdana Font. // BE SURE TO SET THIS AS THE STARTUP PAGE IN THE SOLUTION EXPLORER using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Step3 : System.Web.UI.Page { //---first create a new reference to our datacontext object AdventureworksDataContext dc = new AdventureworksDataContext(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //---create the LINQ SQL to fill the list box var categories = from c in dc.ProductCategories select c; ddlCategory.DataSource = categories; ddlCategory.DataValueField = "ProductCategoryID"; //data table column name ddlCategory.DataTextField = "Name"; //data table column name //---now link up the grid to display our data ddlCategory.DataBind(); //make it so! } } protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e) { //Product_Number below is like a SQL alias var products = from p in dc.Products where p.ProductCategoryID == int.Parse(ddlCategory.SelectedValue) select new { Product_Number = p.ProductNumber, p.Name, p.Color, Price = String.Format("{0:n2}", p.ListPrice)}; //format as currency 2 dec. places & Price as Alias GridView1.DataSource = products; DataBind(); } }