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 year のように、最初の要素に値を追加します

<asp:ListItem Value="0-1">Upto one one year</asp:ListItem>
于 2013-02-27T05:58:46.847 に答える