帶有由鍵連接的兩個不同表的代碼示例:companyID。
public partial class Default : Page
{
public void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var datacontext = new DataClasses1DataContext();
List<Company> companies = datacontext.Companies.ToList();
DropDownList1.DataSource = companies;
DropDownList1.DataValueField = "CompanyID";
DropDownList1.DataTextField = "CompanyName";
DropDownList1.DataBind();
}
}
public void DropDownList1SelectedIndexChanged(object sender, EventArgs e)
{
using (var dc = new DataClasses1DataContext())
{
DetailsView2.DataSource = null;
DetailsView2.DataBind();
DetailsView1.DataSource = dc.Companies.Where(d => d.CompanyID.Equals(DropDownList1.SelectedValue)).ToList();
DetailsView1.DataBind();
List<Contact> contacts =
dc.Contacts.Where(d => d.CompanyID.Equals(DropDownList1.SelectedValue)).ToList();
DropDownList2.DataSource = contacts;
DropDownList2.DataTextField = "LastName";
DropDownList2.DataValueField = "ContactID";
DropDownList2.DataBind();
if (contacts.Any())
{
DetailsView2.DataSource = dc.Contacts.Where(c => c.ContactID.Equals(DropDownList2.SelectedValue)).ToList();
DetailsView2.DataBind();
}
}
}
public void DropDownList2SelectedIndexChanged(object sender, EventArgs e)
{
using (var dc = new DataClasses1DataContext())
{
DetailsView2.DataSource = dc.Contacts.Where(c => c.ContactID.Equals(DropDownList2.SelectedValue)).ToList();
DetailsView2.DataBind();
}
}
}
THX M8 它已經幫助了一堆^^ 現在僅僅是另一個問題 當我重新選擇的東西第二次,它增加了新的項目之前的項目。 有沒有辦法徹底清除下拉列表(除了具有文本值0的第一個項目「做出選擇在這裏」)? – finxie 2012-04-05 08:19:47
酷,我已經做了情景這麼多次,但我記得它是棘手的最初幾次 – 2012-04-05 08:23:25
我清除了ddlMyDropDownList.Items.Clear(整個下拉列表),然後ddlMyDropDownList.Items.Add(新建列表項(「0」,「做出選擇」)) – 2012-04-05 08:27:07