Sunday, September 2, 2012

Color Particular Cell of Gridview

In this Example i will use onRowDataBound property of Gridview to color particular cell.

Just we have call a function on "onRowDataBound" property 
Ex: onRowDataBound="Grid_rowColor"

.aspx Page
 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"  OnRowDataBound="Grid_rowColor">
    <Columns>
    <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" ReadOnly="true" />
    <asp:BoundField DataField="number" HeaderText="number" ReadOnly="true"  SortExpression="number" />

    </Columns>
</asp:GridView>

 <asp:SqlDataSource ID="SqlDataSource1" runat="server"
 ConnectionString="<%$ ConnectionStrings:testchatConnectionString %>"
  SelectCommand="SELECT [name], [number], [id] FROM [testdemo]">
  </asp:SqlDataSource>

.cs page
 public void Grid_rowColor(object sender, GridViewRowEventArgs e)
    {
    if(e.Row.RowType==DataControlRowType.DataRow)
    {
        int value1= Convert.ToInt32(e.Row.Cells[1].Text.ToString());
        if (value1 > 2 && value1 < 30)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Green;
            }
        }
        else if (value1 >= 30 && value1 <= 50)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Gray;
            }

        }
        else
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Yellow;
            }
        }
      }
    }

1 comment: