How To manipulate QueryString Using VB.NET

Discussion in 'Programming' started by largn81, Jan 26, 2008.

  1. #1
    This function will give you 100% control over the QueryString -- perfect for programmers who use QueryString manipulation a lot.

    I wrote this function when I kept having to change values of the QueryString and remove some, add some, etc., etc..

    It takes four (4) parameters:

    oldUrl = the current QueryString you would like manipulated
    qsName = the name of the QueryField you would like to modify/remove/add
    newValue = the new value you would like for the QueryField. set to "" if removing
    del = an optional integer bit flag; if set to 1 it will remove the QueryField/QueryFieldValue from the QueryString.

    Here is the code, enjoy! (I am always welcome to new suggestions)


    Code: ( vbnet )
    Function ChangeValue(ByVal oldUrl As String, ByVal qsName As String, ByVal newValue As String, Optional ByVal del As Integer = 0) As String

    Dim newUrl As String = ""

    ' Check if the [qsName] is currently in the [oldUrl]
    If InStr(oldUrl, qsName & "=")

    oldUrl += "&"

    Dim pos1 As Integer, pos2 As Integer

    If del = 1
    pos1 = oldUrl.IndexOf(qsName & "=")
    pos2 = oldUrl.IndexOf("&", pos1) + 1
    Else
    pos1 = oldUrl.IndexOf(qsName & "=") + qsName.Length + 1
    pos2 = oldUrl.IndexOf("&", pos1)
    End If

    Dim chunk_1 As String = oldUrl.SubString(0, pos1)
    Dim chunk_2 As String = oldUrl.SubString(pos2)

    If del = 1
    newUrl = chunk_1 & chunk_2
    Else
    newUrl = chunk_1 & newValue & chunk_2
    End If

    newUrl = newUrl.SubString(0, (newUrl.Length - 1))

    Else

    If del = 1
    Return oldUrl
    End If

    ' Append the new value to the [oldUrl] and make it a [newUrl]
    If oldUrl.EndsWith("?")
    newUrl = oldUrl & qsName & "=" & newValue
    ElseIf InStr(oldUrl, "?") AndAlso oldUrl.EndsWith("?") = False
    If oldUrl.EndsWith("&")
    newUrl = oldUrl & qsName & "=" & newValue
    Else
    newUrl = oldUrl & "&" & qsName & "=" & newValue
    End If
    Else
    newUrl = oldUrl & "?" & qsName & "=" & newValue
    End If

    End If

    Return newUrl

    End Function


    Here is an example:
    We have the querystring

    Code: ( text )
    http://www.yourdomain.com/search.aspx?fulltext=cat&author=bill+nye&type=scientist&age=45


    Now I want to change the "fulltext" to "dog" and the "author" to "bob dole"
    Also, I want to remove "type" from the QueryString.

    Code: ( vbnet )
    Dim newUrl = Request.RawUrl.ToString()
    newUrl = ChangeValue(newUrl, "fulltext", "dog")
    newUrl = ChangeValue(newUrl, "author", "bob dole")
    newUrl = ChangeValue(newUrl, "type", "", 1)


    The QueryString would now look like this:

    Code: ( text )
    http://www.yourdomain.com/search.aspx?fulltext=dog&author=bob+dole&age=45


    Yes! It's that easy!
    ;):)
     
    largn81, Jan 26, 2008 IP