2

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

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

2 回答 2

4

更新你这样标记

<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 }
}
于 2013-02-27T05:58:32.513 回答
1

Value第一个元素DropDownList是空字符串,当您绑定时,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>
于 2013-02-27T05:58:46.847 回答