ASP.NET Web Form: Index out of range on redirects.

Brown, Matt 126 Reputation points
2025-05-20T14:38:28.03+00:00

I can get either redirect by themselves to work. If I use both of them, I get an error 'Index was out of range. Must be non-negative and less than the size of the collection.' I even separated the code between page preload and page load functions, and I still get the error.

if (Request.QueryString[0] != null)
{
    Response.Redirect("Request.aspx?id=" + Request.QueryString[0]);
}
else
{
    Response.Redirect("Request.aspx");
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,487 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 59,566 Reputation points
    2025-05-20T14:56:00.9833333+00:00

    We have no real context about what you mean by "redirect by themselves", "get an error index" or "even separated the code between page preload and page load". But just a quick glance at your code it seems like you're trying to include an id query string value as part of your redirect and that code isn't correct. If there is no query string (e.g. http://localhost) then you'll get an OOR error because QueryString is empty. There is no first element.

    if (Request.QueryString.Count > 0) {
       Response.Redirect("Request.aspx?id=" + Request.QueryString[0]);
    } else {
       Response.Redirect("Request.aspx");
    }
    

    I'm assuming here that this code isn't on the actual Request.aspx page. If it was then you'd get an infinite loop.


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 76,256 Reputation points Moderator
    2025-05-20T15:27:53.8933333+00:00

    Request.QueryString[0] will throw an error if the array is empty. Try:

    if (Request.QueryString.Count > 0 && Request.QueryString[0] != null)
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.