用斜线'/'拆分字符串 [英] Split string by slash '/'
问题描述
protected void OnRowDataBound123(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell statusCell1 = e.Row.Cells[1];
if (statusCell1.Text != "-")
{
string[] a = statusCell1.Text.Split('/');
if (a[0] != a[1])
{
statusCell1.ForeColor = System.Drawing.Color.Red;
}
}
}
}
我正在使用此功能gridview onrowdatabound,如果/之前和之后的数据不匹配则为红色文本。
我的样本数据:
5/6
11 / 11
-
1/3
但不断收到错误:
i'm using this function in gridview onrowdatabound ,if data before and after / is not match then red color text.
my sample data :
5/6
11/11
-
1/3
but keep getting error :
System.IndexOutOfRangeException: Index was outside the bounds of the array.
我有什么试过:
What I have tried:
protected void OnRowDataBound123(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell statusCell1 = e.Row.Cells[1];
if (statusCell1.Text != "-")
{
string[] a = statusCell1.Text.Split('/');
if (a[0] != a[1])
{
statusCell1.ForeColor = System.Drawing.Color.Red;
}
}
}
}
推荐答案
您好,
只需检查if语句中返回的数组的长度。
Hello ,
Just check the length of the array returned in your if statement .
string[] a = statusCell1.Text.Split('/');
if(a.Length > 1)
{
//do other stuff
}
异常到来作为返回大小小于你正在访问的索引的数组。
这里你正在访问数组元素1然后数组中必须至少有2个元素,因为数组索引从0开始。
谢谢
the exception comes as returning array of size less than the index you are accessing with.
Here you are accessing the array element 1 then there must be atleast 2 elements in the array as array index starts with 0 .
Thanks
这可能是因为你有一个或多个条目不是所需的格式。
只需添加支票为了你继续比较。
类似于 -
That could be because you have one or more entries which is not in the desired format.
Just add a check for you go ahead to compare.
Something like-
if(a.Length>1)
{
if (a[0] != a[1])
{
statusCell1.ForeColor = System.Drawing.Color.Red;
}
}
您还可以在调试时监视值,看看值是多少你得到了。
希望,它有帮助:)
You could also put a watch on the values while debugging to see what are the values you are getting.
Hope, it helps :)
这篇关于用斜线'/'拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!