Click here to Skip to main content
15,919,749 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Dear Friends,

I am displaying a set of records in Gridview from DB.
Eg: Name, Address, Mobile, ID
ID value will be 1 or 2.
If ID is 1 then i want the complete row to be displayed in Red color.
else it should display in Green color.
How to implement this in Gridview.
Kindly guide.
Posted

Try this:

C#
foreach (GridViewRow gvrow in GridView1.Rows)
{
    if(gvrow.Cells["ID"].Value = 1)
    {
          gvrow.DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
          gvrow.DefaultCellStyle.BackColor = Color.Green;          
    }
}
 
Share this answer
 
Hi,

Try this.

VB
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim id As Integer = CType(DataBinder.Eval(e.Row.DataItem, "ID"), Integer)
        Select case ID
            Case = "1"
                e.row.BackColor=Drawing.Color.Green
            Case Else
                e.row.BackColor=Drawing.Color.Red
        End Select
    End If
End Sub
 
Share this answer
 
Comments
Prasad_Kulkarni 9-Jul-12 5:38am    
Question is tagged as C#, not vb
Arunprasath Natarajan 9-Jul-12 6:17am    
Yeah Prasad is rit. But thank you friends from quick response.
Sanjay Kunjam 9-Jul-12 6:33am    
Thanks for positive response.
XML
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  {

    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // cell[]  postion of column having ID
     if( e.Row.Cells[1].Text == "1")
      {
       e.Row.Style.Add("background","red");
      }
    else
      {
       e.Row.Style.Add("background","green");
      }
    }

  }
 
Share this answer
 
There are two ways:
1.
ASP.NET
<asp:gridview id="GridView1" runat="server" cellpadding="4" forecolor="#333333" xmlns:asp="#unknown">
        	GridLines="None" onrowdatabound="GridView1_RowDataBound">
	<alternatingrowstyle backcolor="green" />
	<rowstyle backcolor="Red" />


2.
C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
	if(e.Row.RowType==DataControlRowType.DataRow)
	{
		DataRow dr = (DataRow)e.Row.DataItem;// or MyObject obj = (MyObject)e.Row.DataItem;
		if(dr["id"].ToString() == "1")
		{
			e.Row.CssClass = "redBackground";//or e.Row.Style.Add("background-color", "green");
		}
		else
		{
			e.Row.CssClass = "greenBackground";//or e.Row.Style.Add("background-color", "green");
		}
	}
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900