an improved cascade class that includes methods using both xml and sql
I posted an entry of how to make cascading ddls with xml in the past, now I extended the class to include sql. In this case, one of the few times I may say so I decided not to use LINQ as in this case it actually seemed to make more work. The idea is basically the samejust usingan SQL database. This is what the info in my DB looks like:
dropDowns
| id | category | item |
| 1 |
ford |
mustang |
| 2 |
ford |
f-150 |
| 3 |
ford |
focus |
| 4 |
chevy |
impala |
| 5 |
chevy |
corvette |
| 6 |
chevy |
blazer |
Now I just have to make my ddls, notice the second one is empty:
<asp:DropDownList ID="ddlMake" runat="server" AutoPostBack="true" onselectedindexchanged="ddlMake_SelectedIndexChanged"
cascadeTo="ddlModel" cascadeBlank="- select make -" >
<asp:ListItem>- select make -</asp:ListItem>
<asp:ListItem>ford</asp:ListItem>
<asp:ListItem>chevy</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" Enabled="false" runat="server">
<asp:ListItem>- select make -</asp:ListItem>
</asp:DropDownList>
Also notice that the attributes cascadeTo and cascadeBlank are set. cascadeTo is the ddl you are going to cascade to, and cascadeBlank is what the empty value of the cascaded-to ddl will be if the original is returned to index 0 (that is much easier to demonstrate than explain).
Now just call it in the code-behind (don't forget to put the class in your App_Code folder):
protected void ddlMake_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dll = (DropDownList)sender;
string connString = ConfigurationManager.ConnectionStrings[ "mytestDB" ].ConnectionString;
cascade2.fromThisDropDownSql(this.Page, (DropDownList)sender, connString, "item", "category", "dropDowns" );
}
This takes more inputs than the xml one, but is quite simple if you compare it to the database above. The first two variables will always be the same, and the next 4 are simply the connection string, the table column you wish to populate the cascaded ddl with, the table column that you are filtering with, and the table name. Doesn't really matter how your tables are layed out or where everything is located, you just change your inputs accordingly. Really that is all that it takes.