How to change Gridview row color based on DataKeyName?

Viewed 110

I want to be able to change the row color based on a datakeyname I have set in the ASPX page. This is what I've tried so far and it won't work.

How do I reference the data key name(which is a column in a table I'm calling) and still change the color based on certain text? The column will be hidden in the gridview. Any suggestions?

protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.DataItem.Equals("Example Text"))
        {
            e.Row.BackColor = Color.Green;
        }
        else if (e.Row.DataItem.Equals("Other Text"))
        {
            e.Row.BackColor = Color.Orange;
        }
    }
}
1 Answers

The DataKeyNames are index based.

string dataKeyValue = Gridview1.DataKeys[e.Row.RowIndex].Values[0].ToString();

if (dataKeyValue == "Example Text")
{
     e.Row.BackColor = Color.Green;
}
Related