This article describes changing the color of a GridView
row depending on the value of a column and changing the value of a column depending on the value of that column.
First, let's start with binding a GridView
with data from the database. Create a GridView
.
<asp:GridView ID="grdDoc" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="DOCCODE" Height="40px"
PageSize="8" ShowFooter="True" Visible="false"
onpageindexchanging="grdDoc_PageIndexChanging"
onselectedindexchanged="grdDoc_SelectedIndexChanged" >
<PagerSettings Mode="NumericFirstLast" />
<RowStyle BackColor="WhiteSmoke" BorderColor="CornflowerBlue"
ForeColor="Black" Height="30px" />
<Columns>
<asp:TemplateField HeaderText="Dose">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CommandName="select"
Text='<%#Eval("DOCCODE")%>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DOCNAME" HeaderText="Description" />
<asp:BoundField DataField="DOCDEPT" HeaderText="Description" />
<asp:BoundField DataField="DOCACTIVE" HeaderText="Description" />
</Columns>
<FooterStyle BackColor="Silver" Height="25px" />
<PagerStyle BackColor="DarkGray" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
</asp:GridView>
Load data from a database:
protected void Page_Load(object sender, EventArgs e)
{
string strSQLconnection =
"Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("select DOCCODE,DOCNAME," +
"DOCDEPT, DOCACTIVE from DOCTORS", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
grdDoc.DataSource = reader;
grdDoc.DataBind();
}
Change the color of a row depending on whether the Doctor is Active or Inactive.
protected void grdDoc _RowDataBound(object sender, GridViewRowEventArgs e)
{
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((string.IsNullOrEmpty(e.Row.Cells[3].Text) != true) ||
(e.Row.Cells[3].Text != " "))
{
Char result = Convert.ToInt32(e.Row.Cells[3].Text);
if (result == āYā) e.Row.BackColor = System.Drawing.Color.Aqua;
else if (result ==āNā) e.Row.BackColor = System.Drawing.Color.Cornsilk;
}
}
}
}
First, we need to check if the data in the fourth column is null
or the column is empty. If the Doctor is Active, then the row color will be AQUA. Or else the Color of the row will be CORNSILK.
Change the Color of the cells depending on the Value of a column:
protected void grdDoc _RowDataBound(object sender, GridViewRowEventArgs e)
{
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((string.IsNullOrEmpty(e.Row.Cells[3].Text) != true)
|| (e.Row.Cells[3].Text != " "))
{
string result = Convert.ToInt32(e.Row.Cells[2].Text);
if (result == "M.S")
e.Row.Cells[3].BackColor= System.Drawing.Color. Aquamarine;
else
e.Row.Cells[3].BackColor= System.Drawing.Color. BlanchedAlmond;
}
}
}
}