2014-07-02 25 views
0

这是我的代码1索引打印第二个索引显示错误"Index was outside the bounds of the array."请帮我该怎么办?我怎样才能获取文本框的值在字符串数组和打印

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

'为(INT I = 0; I bumbumpaw

回答

1

你的代码应该是。

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

问题是,SName和Email的长度是不同的。

+0

他也将'SName.Length'减1。 – Shaharyar

+0

@Shaharyar:更新的代码。 –

+1

在这种情况下,不需要长度检查。当长度为0时,for循环不会进入。 – Measuring

2

对于SNameEmail字符串数组,都没有必要得到相同的长度。

Index is out of bound because length are not same

更好的办法是单独做到这一点:

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

如果你想print one name and email然后使用此:

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

注意

如果你不处理数组具有相同名称的HTML元素,则不必使用Request.Form.GetValues("title")。见下面的例子:

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

Response.Write(SName + " " + Email); 
0

可以使用下面的代码,它给出结果在单个环路

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]); 
    } 
} 
相关问题