Refer the following.
Database
I have made use of the following table Students with the schema as follows.
I have already inserted few records in the table.
You can download database SQL from here.
HTML
<asp:GridView runat="server" ID="gvStudents" AutoGenerateColumns="false" OnRowDataBound="Students_RowDataBound"
Width="289px">
<Columns>
<asp:BoundField DataField="StudentId" HeaderText="Student Id" />
<asp:BoundField DataField="StudentName" HeaderText="Student Name" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("Status") %>' Width="20px" ForeColor = "White" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetStudents();
}
}
protected void Students_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
Label lblStatus = (Label)e.Row.FindControl("lblStatus");
switch (lblStatus.Text)
{
case "P":
lblStatus.BackColor = Color.Green;
break;
case "A":
lblStatus.BackColor = Color.Red;
break;
}
}
}
private void GetStudents()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT StudentId, StudentName, [Status] FROM Students", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtStudents = new DataTable();
sda.Fill(dtStudents);
this.gvStudents.DataSource = dtStudents;
this.gvStudents.DataBind();
}
}
}
}
Screenshot
