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

标签 c# asp.net 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]);
}

这给了我异常(exception)

"Index was outside the bounds of the array."

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

关于c# - 分割字符串时索引超出范围异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105163/

相关文章:

c# - 设计 gem 迷阵游戏的问题

asp.net - 如何在 ASP.NET Core 中为电子邮件创建动态链接

python - 从 pandas 数据框中的字符串中提取信息非常困难

c++ - std::shared_ptr<std::string const> 能否作为引用计数不可变字符串的有效实现?

c# - DropDownList Bootstrap 样式

c# - 如何在 Kentico CMS 中创建 "back"链接?

c# - 从 C# 连接和使用 sqlite 数据库的最佳方法是什么

c# - 从 ListView 控件获取索引项

c# - ASP.NET:动态生成 HTML,如何?

MySQL schedule update 语法错误?