繁体   English   中英

分割字符串时索引超出范围异常

[英]Index was out of bounds exception in splitting string

我写了这段代码来分割字符串

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

这样更新您的标记

<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 }
}

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM