Reputation: 124
In my ASP.NET folder i have 3 dropdownboxes who are filled with sorts of categories with 3 different SQLdatascources. Each dropdownlist depends on the one above it.
The intention of this thing is that after selecting something in dropdownlist1, the datasource in dropdownlist2 changes. So the data in dropdown2 depend on the selected value in dropdown1. And the data in dropdown3 depend on the selected value in dropdown2.
It all works nice and dandy a first time. But when I selected a value in dd1 and after this a value in dd2, it starts to fail.
When I change the value a second time in dropdown1 for example, the other dropdownlists don't alter.
Thx in advance for replies
Upvotes: 2
Views: 916
Reputation: 16
Example of code with 2 different tables connected by keys, in this example: 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();
}
}
}
Upvotes: 0
Reputation: 2855
Put the code to fill dd2
in the OnSelectedIndexChanged
of dd1
, and do the same for the OnSelectedIndexChanged
of dd2
(to fill dd3
).
Upvotes: 0
Reputation: 3098
To do this kind of thing, you need to make sure your top level drop down list is only populated once, so put it in the page load with a !isPostback around it. Then attach a OnSelectedIndexChanged() event on that top level dropdownlist, and in it, be sure to clear the items in the second level dropdown list before setting it's new datasource.
Then a OnSelectedIndexChanged() on the second level dropdown list, and be sure to clear the third before populating it.
Then the third doesn't need any events.
Upvotes: 4