2013-02-27 98 views
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> 
+0

你調試呢?當你在那裏放置一箇中斷點時,你可以在同一行的「exp」中看到什麼值? – gaurav 2013-02-27 05:57:36

+0

這意味着'exp'沒有第二個元素。檢查'exp.Length' – 2013-02-27 05:57:42

+0

什麼是在你的下拉列表中的空白? – gaurav 2013-02-27 05:58:51

回答

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

The 的第一個元素的爲空字符串,並且當您綁定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>