0

this is my code 1 index print second index showing error "Index was outside the bounds of the array." please help what should I do?

string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");

for (int i = 0; i <= SName.Length - 1; i++)
{
     Response.Write(SName[i]);
     Response.Write(Email[i]);
}
1
  • 1
    for (int i = 0; i < SName.Length - 1; i++) remove the equal sign on your condition. Commented Jul 2, 2014 at 5:53

3 Answers 3

2

It is not necessary you get same length for both SName and Email string arrays.

Index is out of bound because length are not same.

Better way is to do it separately:

string[] SName = Request.Form.GetValues("title");
string[] Email = Request.Form.GetValues("fname");

for (int i = 0; i < SName.Length; i++)        
   Response.Write(SName[i]);       

for (int i = 0; i < Email.Length; i++)
   Response.Write(Email[i]);

If you want to print one name and email then use this:

 string[] SName = Request.Form.GetValues("title");
 string[] Email = Request.Form.GetValues("fname");
 int iLength = -1; 

 if(SName.Length > Email.Length) 
     iLength = SName.Length;
 else
    iLength = Email.Length;

 for (int i = 0; i < iLength; i++)
 {
     if(i < SName.Length)
        Response.Write(SName[i]);          
     if(i < Email.Length)
        Response.Write(Email[i]);
 }

NOTE:

If you are not dealing with array of HTML element with same name then you don't have to use Request.Form.GetValues("title"). See following example:

string SName = Request.Form["title"];
string Email = Request.Form["fname"];

Response.Write(SName + " " + Email);
Sign up to request clarification or add additional context in comments.

Comments

1

Your code should be.

if (SName != null)    
    for (int i = 0; i < SName.Length; i++)
        Response.Write(SName[i]);

if (Email != null)
    for (int i = 0; i < Email.Length; i++)
        Response.Write(Email[i]);

The problem is that length of SName and Email are different.

2 Comments

He is also decreasing SName.Length by 1.
In this case, the length check would not be needed. The for loop won't enter when the length is 0.
0

You can use the below code, which gives the result in a single loop

if (SName != null && SName.Length > 0 && Email != null && Email.Length > 0)
{
     for (int i = 0,j=0; i < SName.Length && j<Email.Length; i++,j++)
     {
          Response.Write(SName[i]);
          Response.Write(Email[j]);
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.