We created a new empty web site. First we added a new web form. Then we added a new Link To SQL Classes. From the View Menu we added the Server Explorer. In it we right clicked on Data Connections and added a new Data connection to the Automart Database. Then we dragged the Employee, Location and Person tables onto the designer
To the web form we added a drop down list and a Grid view. Here is the code for the web page.
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Employees</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList><br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
Here is the code behind, using the LINQ syntax. Notice its resemblance to SQL.
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
automartDataContext dc = new automartDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDropDown();
}
}
protected void FillDropDown()
{
var local = from l in dc.Locations
orderby l.LocationName
select new { l.LocationName, l.LocationID };
DropDownList1.DataSource = local.ToList();
DropDownList1.DataTextField = "LocationName";
DropDownList1.DataValueField = "LocationID";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "Select Location");
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var emp = from ee in dc.Employees
orderby ee.Person.LastName
where ee.LocationID==int.Parse(DropDownList1.SelectedValue.ToString())
select new { ee.Person.LastName, ee.Person.FirstName, ee.HireDate };
GridView1.DataSource = emp.ToList();
GridView1.DataBind();
}
}
Here is a picture of the program running:
No comments:
Post a Comment