views:

45

answers:

4

Hey,

I have this url : http://localhost:49500/Learning/Chapitre.aspx?id=2

How can I get just the value of id in this url ?

A: 

Create a new instance of System.Uri class with the URL and the use the Query property to get the query string part.

Once you have that string, do String.Split on the '&' character. For each string in the resulting array, do String.Split on the '=' char. In the resulting array, the first string is the query parameter name, the second is the value (if present). Check if the name is the one you are interested in and if it is, get the value.

Update: Boy, I haven't touched VB since 1999... :-)

Here's the code for my answer. I didn't realize that the Url you want to parse is the page Url. For that specific case, Request.QueryString("id") will indeed be a better solution.

    Dim url As Uri = New Uri("http://localhost:49500/Learning/Chapitre.aspx?id=2")
    Dim query As String = url.Query.Trim("?")
    Dim parameters() As String = query.Split("&")
    Dim tokens() As String
    Dim value As String = ""
    For index As Integer = 0 To parameters.Length - 1
        tokens = parameters(index).Split("=")
        If tokens(0).ToLower = "id" Then
            If tokens.Length = 2 Then
                value = tokens(1)
            End If
            Exit For
        End If
    Next
    ' At this point value contains the parameter value or
    ' is empty if the parameter has no value or if the parameter is not present
Franci Penov
examples please ?
dotNET
A: 

Despite my own comment saying it has been answered, here is the code.

Dim idval As String = System.Web.HttpUtility.ParseQueryString("http://localhost:49500/Learning/Chapitre.aspx?id=2")("id")
Patricker
+2  A: 

you can access all the query strings through the Request.QueryString() array:

Request.QueryString("id") will give you the "2"

Jaime
Thank you, It's working.
dotNET
A: 

If you want examples of how to parse and get the values out of any URL, how about plugging it into URLParser.com.

URLParser.com