Search code examples
asp.netvb.neturlcode-behind

How to create a link to a website in vb code behind?


It may be simple but the search words in Google give too many irrelevant results.

Protected Sub Menu1_MenuItemClick(sender As Object, e As MenuEventArgs) Handles Menu1.MenuItemClick
    If e.Item.Text = "SomeItem" Then
      'The link goes here
    End If
End Sub

Solution

  • Use Response.Redirect if you want to send the current page to a new url:

    Protected Sub Menu1_MenuItemClick(sender As Object, e As MenuEventArgs) Handles Menu1.MenuItemClick
        If e.Item.Text = "SomeItem" Then
            Response.Redirect("http://www.stackoverflow.com")
        End If
    End Sub
    

    To open a new url in a new window/tab you would have to use javascript. Normally I would recommend just putting the javascript directly onto the aspx page but in the event that the url will use data from the code behind to generate the url you can use the ClientScript.RegisterStartupScript function.

    Protected Sub Menu1_MenuItemClick(sender As Object, e As MenuEventArgs) Handles Menu1.MenuItemClick
        If e.Item.Text = "SomeItem" Then
            Dim sURL As String = "http://www.stackoverflow.com"
            ClientScript.RegisterStartupScript(Me.GetType(), "script", "window.open('" & sURL + "', 'popup_window');", True)
        End If
    End Sub