Muhammad Anas
Muhammad Anas

Reputation: 1

how can i fetch text box value in string array and print

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]);
}

Upvotes: 0

Views: 137

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48580

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.

Upvotes: 1

Hassan
Hassan

Reputation: 5430

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);

Upvotes: 2

Aju Mon
Aju Mon

Reputation: 235

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]);
     }
}

Upvotes: 0

Related Questions