我编写了用于分割字符串的代码
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/