views:

44

answers:

2

I am displaying student attendance in Grid view.

I choose absent as A, present as P and leave as L. Now i would like to display A in red color, P in green.

How is it. please help me

+1  A: 

please try this and let me know what issue you face

protected void grdStudent_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRow dr = ((DataRowView)e.Row.DataItem).Row;
        if (dr["Present"].ToString() == "A")
        {
            ((Label)e.Row.FindControl("yourLableID")).ForeColor= System.Drawing.Color.Red;
        //yourLableID is that lable in which you are showing A or P
        }
    }
}
Muhammad Akhtar
+1  A: 

My favorite way is to set the color in markup,

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
       <Columns>
        <asp:TemplateField>
         <ItemTemplate>
          <asp:Label runat="server" ID="lblStatus" 
              Text='<%# Eval("Status") %>' 
              ForeColor='<%# GetItemColor(Eval("Status")) %>' />
         </ItemTemplate>
        </asp:TemplateField>
       </Columns>
      </asp:GridView>

based on a method in the code behind

protected System.Drawing.Color GetForeColor(object statusObj)
{
    System.Drawing.Color color = System.Drawing.Color.Black;

    switch ((string)statusObj)
    {
        case "A": color = System.Drawing.Color.Red; break;
        case "P": color = System.Drawing.Color.Green; break;
        case "L": color = System.Drawing.Color.Yellow; break;
    }

    return color;
}

Alternatively you could put the logic directly in the markup, but i prefer to keep as much of the c# code in the .cs file.
Also, asp:TemplateField gives you more flexibility than asp:BoundField.

You can also set the BackColor property for better visibility, But my favorite is adding a small asp:Image, where the ImageUrl property is switched in the same way, between 3 images representing status.

Marwan