问题
I have what I thought would be a simple problem but cannot find an appropriate example after much searching. Put simply, it is a windows form application with 2 databound combo boxes on the form with the first being for "Department" and the second for "Section". These combos are each bound to the corresponding tables in a SQL database. The combos should operate with the user selecting Department from the first which causes the second combo to be filtered to show only sections belonging to that department. (In other words this is the classic "cascading" combo boxes problem). My experience is originally with Delphi and this was a simple design time issue.
However, in C# I am stuck and just can't get it to work. I would have thought that this could be done at design time with maybe some minimal code behind the SelectedIndexChanged event. I would be most grateful if anyone has a basic (form, 2 comboboxes, simple data sources) example of this they can point me to.
Thanks, James
回答1:
ComboBox cbDepartment = new ComboBox();
cbDepartment.Name = "cbDepartment";
cbDepartment.DataSource = dsDepartments;
cbDepartment.SelectedIndexChanged = new System.EventHandler(cbDepartment_SelectedIndexChanged);
private void cbDepartment_SelectedIndexChanged(object sender, System.EventArgs e) {
cbSection.DataSource = GetSection(cbDepartment.SelectedItem.Value);
}
You can try something like the above.
回答2:
You didn't specify what you were binding to. I always bind to objects, so here is how I do it:
In the form load event:
ddlParent.DataSource = new BindingSource(myIEnumerable, null);
And the event handler for the parent combobox:
private void ddlParent_SelectedIndexChanged(object sender, EventArgs e)
{
ddlChild.DataSource = new BindingSource((MyBoundType)ddlParent.SelectedItem, null);
}
I don't know any way to do it at design time.
You should probably override the ToString() method of the objects bound to the drop down list to control the text that is displayed in the combobox.
来源:https://stackoverflow.com/questions/6850932/c-sharp-setting-up-data-bound-cascading-combo-boxes-at-design-time