Home > .net 2.0, c#, Visual Studio 2005 > Dynamically Setting a GridView Cell Background

Dynamically Setting a GridView Cell Background

September 26, 2007

Whether it be from a database image or directly from the file system, it’s sometimes useful to dynamically set the background of a cell to a specific image or color.

If you have a particular color or image located in a datatable and want to use that to dynamically set the background-image or background-color of the cells, the RowDataBound event can help.

For this example, our data table has two columns: LogoImage and DeptName.

dt.Rows.Add(“logo2.gif”, “Web Development”);

dt.Rows.Add(“logo3.gif”, “Student Achievement”);

Easy enough (and also images I had sitting around).  Our GridView control has two bound columns; however, the LogoImage column (the one with logoN.gif) is hidden via CSS.  You can’t set Visible=”false” on the column because then it becomes inaccessible to your code. 

 

<style type=”text/css”>

.HiddenColumn { display: none; }

</style>

 

<asp:GridView ID=”GridView1″ runat=”server”

onrowdatabound=”GridView1_RowDataBound”

        AutoGenerateColumns=”False”>

<Columns>

<asp:boundfield DataField=”LogoImage”>

              <HeaderStyle CssClass=”HiddenColumn” />

               <ItemStyle CssClass=”HiddenColumn” />

               <FooterStyle CssClass=”HiddenColumn” />

               <ControlStyle CssClass=”HiddenColumn” />

</asp:boundfield>

        <asp:BoundField DataField=”DeptName”

              HeaderText=”Department”

       ItemStyle-Width=”500px”

              ItemStyle-Height=”200px” />

</Columns>

</asp:GridView>

Now, the RowDataBound event provides us with a quick way to loop through each row and set attributes specific to that row and it’s cells.

 

protected void GridView1_RowDataBound(object sender,

            GridViewRowEventArgs e)

{

// We don’t want to apply this to headers.

if (e.Row.RowType == DataControlRowType.DataRow)

{

try

{

string imageName = e.Row.Cells[0].Text.ToString();

e.Row.Cells[1].Attributes.Add(“Style”,

   “background-image: url(‘images/” + imageName + “‘);”);

}

catch { }

}

}

At this point, you could customize the background-image tag for repeating, alignment, etc. depending on your needs.

  1. Marta Paniti
    March 10, 2008 at 12:47 am

    Hi!
    Thanks. This article was useful to me🙂

  2. Siriwan
    March 24, 2008 at 3:02 am

    Thank you very much. this article can help me for setting header:

    if (e.Row.RowType == DataControlRowType.Header)
    {
    try
    { e.Row.Attributes.Add(“Style”, “background-image: url(‘images/TableHeaderBg.jpg’);”); }
    catch { }
    }

  3. February 5, 2009 at 11:21 pm

    nice site you have!

  4. March 16, 2009 at 9:15 am

    Very helpful, thank you – was expecting to dig quite a while for this🙂

  1. No trackbacks yet.
Comments are closed.
%d bloggers like this: