How to update querystring in C#?

Solution 1:

To modify an existing QueryString value use this approach:

var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly

I go into more detail in another response.

Solution 2:

Retrieve the querystring of sortby, then perform string replace on the full Url as follow:

string sUrl = *retrieve the required complete url*
string sCurrentValue = Request.QueryString["sortby"];
sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue);

Let me know how it goes :)

Good luck

Solution 3:

    private void UpdateQueryString(string queryString, string value)
    {
        PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
        isreadonly.SetValue(this.Request.QueryString, false, null);
        this.Request.QueryString.Set(queryString, value);
        isreadonly.SetValue(this.Request.QueryString, true, null);
    }