如何获取字符串数组中的文本框值并打印

时间:2014-07-02 05:50:32

标签: c# asp.net arrays

这是我的代码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]);
}

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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和电子邮件的长度不同。

答案 2 :(得分: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]);
     }
}