Redirect a user to a new page when the user selects a file name from a DropDown-List control

133 Views Asked by At

.aspx code:

<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem value="">About Us</asp:ListItem>
            <asp:ListItem Value="1">Contact</asp:ListItem>
        </asp:DropDownList>
    </div>
</form>

.aspx.vb code:

Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs)
    If DropDownList1.SelectedValue = "1" Then
        Response.Redirect("Contact.aspx")
    End If
End Sub

When I click on contact from the dropdown menu, it is not redirecting me to the other page, please help.

2

There are 2 best solutions below

1
On

On your DropDownList you need to include AutoPostBack="True" to tell the server to postback to the server. Also you need to assign the event name using OnSelectedIndexChanged

For example:

  <asp:DropDownList ID="DropDownList1"
             runat="server"
             AutoPostBack="true"
             OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
         <asp:ListItem value="">About Us</asp:ListItem>
         <asp:ListItem Value="1">Contact</asp:ListItem>
 </asp:DropDownList>
1
On

When the combo box changes (dropdownlist), it will NOT run or fire the selected index code stub UNLESS you tell the control to post back to the web server.

So, you need to set this value to true:

enter image description here

You can change the setting in the property sheet, or in your markup, do this:

<div>
  <asp:DropDownList ID="DropDownList1" runat="server" Height="23px" Width="118px"
    AutoPostBack="True">
    <asp:ListItem value="">About Us</asp:ListItem>
    <asp:ListItem Value="1">Contact</asp:ListItem>
        </asp:DropDownList>
</div>

So, note how you need to have a AutoPostBack = "True". If you don't do this, then you can change the dropdown list, but without a post back, then the selected index code stub will NOT run.

Also, as a FYI, selected index starts at 0. But, you can use SelectedValue if you not interested in doing things by index, but want to use the "value" you set. And note that if you use value="", then value will take on the Text you have - in your case "About Us". So often people will just use the text in list item, but you can assign a actual value if you wish to over-ride the Selected value.