[c#] How to use the DropDownList's SelectedIndexChanged event

I have two DropDownLists in my webform and when I select a value in the first dropdownlist, I would like a related value to be automatically selected in the second dropdownlist.

This is what I currently have:

    <table>   
        <tr>
            <td>
                <asp:Label ID="lbmanu" runat="server" Text="Furniture Manufacturer : 
                   "></asp:Label>
            </td>
            <td>
                <asp:DropDownList ID="ddmanu" runat="server" 
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>
                <asp:SqlDataSource ID="Sql_fur_model_manu" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:conStr %>" 
                    SelectCommand="SELECT DISTINCT [manufacturer] FROM 
                     [furniture_manufacturer]">
                </asp:SqlDataSource>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lbtype" runat="server" Text="Furniture Type : 
                        "></asp:Label>
            </td>
            <td>
                <asp:DropDownList ID="ddtype" runat="server" AutoPostBack="True">
                   </asp:DropDownList>
            </td>
        </tr>
   </table>

Code Behind :

protected void ddmanu_SelectedIndexChanged(object sender, EventArgs e)
{
    string query = "select furniture from furniture_model where manufacturer='" + 
    ddmanu.SelectedValue.ToString() + "'";
    con.Open();
    cmd = new SqlCommand(query, con);
    DataTable dt = Select(query);
    cmd.ExecuteNonQuery();
    ddtype.DataSource = dt;
    ddtype.DataTextField = "manufacturer";
    ddtype.DataValueField = "furniture";
    ddtype.DataBind(); 
}

This question is related to c# asp.net webforms event-handling

The answer is


The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

You should add AutoPostBack="true" to DropDownList1

                <asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
                    DataSourceID="Sql_fur_model_manu"    
                    DataTextField="manufacturer" DataValueField="manufacturer" 
                    onselectedindexchanged="ddmanu_SelectedIndexChanged">
                </asp:DropDownList>

I think this is the culprit:

cmd = new SqlCommand(query, con);

DataTable dt = Select(query);

cmd.ExecuteNonQuery();

ddtype.DataSource = dt;

I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":

cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();

Or you can create a DataTable as explained here:

cmd = new SqlCommand(query, con);

SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);

ddtype.DataSource = listTable;

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to webforms

ASP.NET Button to redirect to another page How to use the DropDownList's SelectedIndexChanged event "Specified argument was out of the range of valid values" The ScriptManager must appear before any controls that need it Check if Cookie Exists How to do a Jquery Callback after form submit? "The given path's format is not supported." A potentially dangerous Request.Path value was detected from the client (*) How to create <input type=“text”/> dynamically Create a HTML table where each TR is a FORM

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?