gridview基于值更改文本颜色

时间:2016-10-27 01:11:09

标签: c# asp.net gridview substring

我使用onRowDataBound更改文本的文字颜色,如下所示,但面临一些问题..

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

enter image description here

我在异常详细信息中收到错误:System.IndexOutOfRangeException:索引超出了数组的范围。 我想在这里做的是比较斜线前后的值" /"如果彼此不匹配则文本颜色将变为红色,否则为黑色。

3 个答案:

答案 0 :(得分:0)

您似乎正在尝试在TableCell上应用String.Split

尝试statusCell1.Text.Split(' /')

(或类似于.Text的内容,如果它不起作用。)

//Creating values for testing
//These are just for testing do not place this in your code
TableCell statusCell1 = new TableCell();
statusCell1.Text = "blah/blah blah";

//##################################
//These are the only lines you need
string[] splitString = statusCell1.Text.Split('/');
string resultingString = splitString[0];
string resultingString2 = splitString[1];
//##################################

//These are just for testing do not place this in your code
Console.WriteLine(resultingString);
Console.WriteLine(resultingString2);

//prints out: 
//blah 
//blah blah

答案 1 :(得分:0)

直接从行单元格中获取值,请尝试下面的内容,进行测试:

protected void OnRowDataBound123(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string cellValue = statusCell1 = e.Row.Cells[1].Text;
        if (cellValue != "-")
        {
            string[] a = cellValue.Split('/');
            if (a[0] != a[1])
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}

答案 2 :(得分:0)

 protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        //System.Diagnostics.Debugger.Launch();
        for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
        {
            Label lblparent = (Label)GridView1.Rows[i].FindControl("lblRate");
            if (lblparent.Text != "-")
            {
                string[] a = lblparent.Text.Split('/');
                if (a[0] != a[1])
                {
                    lblparent.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    lblparent.ForeColor = System.Drawing.Color.Green;
                }
            }


        }
    }

这段代码解决了我的问题。