Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change cell color on different values - Gridview

I need to distinguish two consecutive cells.

Each one in a row, if they have different values, when databindind the values to a gridview.

So, if in the row 1 I have the cell "ABC" and in the row 2 I have the cell "CBA".

I need to color each cell with a different color.

What is the best way to do it?

like image 582
Filipe Costa Avatar asked Dec 13 '10 10:12

Filipe Costa


4 Answers

This is called Conditional Formatting

You can enable the RowDataBound Event in the markup

<asp:GridView ID="gridview1" runat="server" OnRowDataBound="RowDataBound">

</asp:GridView>

And put this in your Code-Behind file.

protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        if(e.Row.RowIndex == 0)     // This is row no.1
            if(e.Row.Cells[0].Text == "ABC")
                e.Row.Cells[0].BackColor = Color.Red;

        if(e.Row.RowIndex == 1)     // This is row no.2
            if(e.Row.Cells[0].Text == "CBA")
                e.Row.Cells[0].BackColor = Color.Green;
    }
}
like image 122
Ken D Avatar answered Oct 18 '22 23:10

Ken D


Add to your gridview in html part of page OnRowDataBound="gridView1_DataBinding". And then add event handler codebehind:

protected void gridView1_DataBinding(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType != DataControlRowType.DataRow) return;

        var c = e.Row.FindControl("IdOfControl") as Label;
        if(c != null)
        {
            if (c.Text == "ABC")
                e.Row.BackColor = GetColor("Gray");

            if (c.Text == "BCA")
                e.Row.BackColor = GetColor("Green");
        }
    }

    private Color GetColor(string color)
    {
        return Color.FromName(color);
    }

Best regards, Dima.

like image 4
Dima Shmidt Avatar answered Oct 18 '22 22:10

Dima Shmidt


if i understand you right, you want to change the color of a cell, depending on it's value. if that's correct, you could try it like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if ((Label)e.Row.Cells[0].FindControl("ValueHoldingControl").Text == "ABC")
        {
            //Coloring the cell
        }
    }
}
like image 2
chris vietor Avatar answered Oct 18 '22 23:10

chris vietor


you can do it on the rowdatabound event of the gridview. Keep the previous row in viewstate or session and match it with the next row. If it does't match, change the color otherwise don't change.

like image 1
sam Avatar answered Oct 18 '22 22:10

sam