Publish Article

Formatting Grid View - Change appearance of columns programatically


If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to become a Winista member and download the control for free.

This article will help answer lot of common questions that a lot of developers ask about formatting of GridView control's columns.

  • Setting BackColor of GridView Programtically
  • How to change forecolor, backcolor etc. of GridView column based on some run time conditions or values?
  • How can I change style associated with GridView cell at run time?

Answer to all the above question lies in handling event like RowCreated and implementing event handler for it OnRowCreated. When you want to handle this event your tags for GridView control look something like following code snippet.

<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />						

And in your code behind you can add implementation similar to what I have in the demo project attached with this article. Notice the code demonstrates two solutions. It sets style sheet for the cell and then it uses BackColor property of cell to set the background color.

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.DataRow)
        DataRowView drv = e.Row.DataItem as DataRowView;
        Object ob = drv["Weight"];
        if (!Convert.IsDBNull(ob) )
            double dVal = 0f;
             if (Double.TryParse(ob.ToString(), out dVal))
                 if (dVal > 3f)
                     TableCell cell = e.Row.Cells[1];
                     cell.CssClass = "heavyrow";
                     cell.BackColor = System.Drawing.Color.Orange;
Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix