我已经编写了用于拆分字符串的代码。
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>发布于 2013-02-27 05:58:32
更新你的标记像这样
<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-27 05:58:46
第一个元素的Value是空字符串,当您绑定时,将为第一个元素触发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>https://stackoverflow.com/questions/15105163
复制相似问题