In this article I will explain with an example, how to use the
SelectedIndexChanged event of
ASP.Net DropDownList in C# and VB.Net.
The
SelectedIndexChanged event of will work / fire / trigger only when the
AutoPostBack property of the
ASP.Net DropDownList is set to True.
HTML Markup
The following
HTML Markup consists of:
DropDownList – For selecting Fruits.
The
DropDownList specified with
OnSelectedIndexChanged event handler and
AutoPostBack property set to True.
<asp:DropDownList ID="ddlFruits" runat="server" AutoPostBack="true" OnSelectedIndexChanged="OnSelectedIndexChanged">
<asp:ListItem Text="Mango" Value="1" />
<asp:ListItem Text="Apple" Value="2" />
<asp:ListItem Text="Banana" Value="3" />
<asp:ListItem Text="Guava" Value="4" />
<asp:ListItem Text="Orange" Value="5" />
</asp:DropDownList>
The SelectedIndexChanged event of ASP.Net DropDownList
When an item is changed in
ASP.Net DropDownList, the following
OnSelectedIndexChanged event handler is executed.
Inside the event handler, the selected
Text and Value of the
DropDownList Selected Item is fetched and displayed using
JavaScript Alert message box.
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string message = ddlFruits.SelectedItem.Text + " - " + ddlFruits.SelectedItem.Value;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true);
}
VB.Net
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs)
Dim message As String = ddlFruits.SelectedItem.Text & " - " & ddlFruits.SelectedItem.Value
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" & message & "');", True)
End Sub
Screenshot
Downloads