CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Conditionally Formatting GridView Row based on a Column value in ASP.Net
Submitted By Satheesh Babu B
On 3/1/2010 8:07:02 AM
Tags: ASP.Net,CodeDigest,GridView  

Conditionally Formatting GridView Row based on a Column value in ASP.Net

 

Sometimes, we will require highlighting GridView control's row based on a value in particular column. For example, highlighting only admin users in a users list or highlighting all permanent employees from employees list that has both permanent and contract employees in Employee table.

ASPX

<asp:GridView ID="gvUsers" runat="server" onrowdatabound="gvUsers_RowDataBound">
    </asp:GridView>

CodeBehind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUsers();
        }
    }
    public void BindUsers()
    {
        DataTable dt = GetUsersForModeration();       
        gvUsers.DataSource = dt;
        gvUsers.DataBind();
    }
    public DataTable GetUsersForModeration()
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("SP_GetUsersForModeration", con);
        com.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter ada = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        ada.Fill(ds);
        return ds.Tables[0];
    }
    protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.Cells[3].Text == "Admin")
            {
                e.Row.BackColor = System.Drawing.Color.Orange;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }

 

The above code will make all admin user's row background color to orange and foreground color to white.
Note
The above code "e.Row.Cells[3].Text" in RowDataBound event will not work if the column text we are fetching is template column. In this case, use DataBinder.Eval(e.Row.DataItem,"Role") to fetch the text. Hence, the above code will become,
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (DataBinder.Eval(e.Row.DataItem,"Role")== "Admin")
            {
                e.Row.BackColor = System.Drawing.Color.Orange;
                e.Row.ForeColor = System.Drawing.Color.White;
            }
        }
    }


The above code will work fine for databound column also.

 

Happy Coding!!!

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..