首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >索引在拆分字符串中超出了异常范围。

索引在拆分字符串中超出了异常范围。
EN

Stack Overflow用户
提问于 2013-02-27 05:54:55
回答 2查看 1.4K关注 0票数 2

我已经编写了用于拆分字符串的代码。

代码语言:javascript
运行
复制
 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]);线上

代码语言:javascript
运行
复制
        <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>
EN

回答 2

Stack Overflow用户

发布于 2013-02-27 05:58:32

更新你的标记像这样

代码语言:javascript
运行
复制
<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并检查拆分数组的长度

代码语言:javascript
运行
复制
//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 }
}
票数 4
EN

Stack Overflow用户

发布于 2013-02-27 05:58:46

第一个元素的Value是空字符串,当您绑定时,将为第一个元素触发SelectedIndexChanged事件,并将其拆分为零元素数组。在按索引访问数组之前对索引应用条件。

代码语言:javascript
运行
复制
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年。

代码语言:javascript
运行
复制
<asp:ListItem Value="0-1">Upto one one year</asp:ListItem>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15105163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档