【问题标题】:how can i fetch text box value in string array and print如何在字符串数组中获取文本框值并打印
【发布时间】:2014-07-02 05:50:31
【问题描述】:

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

【问题讨论】:

  • for (int i = 0; i &lt; SName.Length - 1; i++) 删除条件上的等号。

标签: c# asp.net arrays


【解决方案1】:

SName 和 Email 字符串数组的长度不必相同。

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

【讨论】:

    【解决方案2】:

    你的代码应该是。

    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 的长度不同。

    【讨论】:

    • 他也减少了SName.Length 1。
    • 在这种情况下,不需要长度检查。长度为0时for循环不会进入。
    【解决方案3】:

    您可以使用下面的代码,它在一个循环中给出结果

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多