【问题标题】:Index was out of bounds exception in splitting string拆分字符串时索引超出范围异常
【发布时间】:2013-02-27 05:54:55
【问题描述】:

我已经写了这个分割字符串的代码

 protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    string oldstr = DropDownList2.SelectedItem.Value;

    string[] exp = System.Text.RegularExpressions.Regex.Split(oldstr, "-");
    int int1 = Convert.ToInt32(exp[0]);
    int int2 = Convert.ToInt32(exp[1]);
}

它给了我例外

“索引超出了数组的范围。”

在线int int2 = Convert.ToInt32(exp[1]);

        <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" 
                onselectedindexchanged="DropDownList2_SelectedIndexChanged">
                <asp:ListItem></asp:ListItem>
                <asp:ListItem Value="1-2">1-2 years</asp:ListItem>
                <asp:ListItem Value="3-4 ">3-4 years</asp:ListItem>
                <asp:ListItem Value="5-7">5-7 years</asp:ListItem>
            </asp:DropDownList>

【问题讨论】:

  • 你调试了吗?将断点放在那里时,您可以在同一行的“exp”中看到什么值?
  • 这意味着exp 没有第二个元素。检查exp.Length
  • 那么一个空的 在你的下拉列表中做了什么?

标签: c# asp.net string


【解决方案1】:

更新你这样标记

<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" 
                onselectedindexchanged="DropDownList2_SelectedIndexChanged">
         <asp:ListItem Value="0-0"></asp:ListItem> // add 0 and 0
        <asp:ListItem Value="1-2">1-2 years</asp:ListItem>
        <asp:ListItem Value="3-4">3-4 years</asp:ListItem>//remove space after 4 
        <asp:ListItem Value="5-7">5-7 years</asp:ListItem>
</asp:DropDownList>

而不是像下面那样转换使用 TryParse 并检查拆分数组的长度

//string[] exp = System.Text.RegularExpressions.Regex.Split(oldstr, "-");
//use string split rathre than using regular expression because character split is 
// faster than regular expression split
string[] exp = oldstr.Split('-');
if(exp.Length>0)
{
  int int1;
  if(int.TryParse(exp[0], out num1))
 { // further code }
  int int2;
 if(int.TryParse(exp[1], out num1))
 { // further code }
}

【讨论】:

    【解决方案2】:

    DropDownList 的第一个元素的Value 是空字符串,当你绑定SelectedIndexChanged 事件时,第一个元素会被触发,拆分它会给你一个零元素数组。在按索引访问数组之前对索引应用条件。

    int int1 = 0;
    if(exp.Length > 0)
         int1 = Convert.ToInt32(exp[0]);
    
    int int2 = 0;
    if(exp.Length > 1)
         int2 = Convert.ToInt32(exp[1]);
    

    或者为第一个元素添加值,例如 0-1 年

    <asp:ListItem Value="0-1">Upto one one year</asp:ListItem>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      相关资源
      最近更新 更多