Change or highlight Asp.net Repeater cell background color based on condition

Highlight or change asp.net repeater column background color based on condition
Click on image to enlarge
Introduction: In this article i am going to share the code example to highlight or change table column/cell background and text color in Repeater Data control based on some condition in asp.net using both C# and VB languages.

Basically you will learn the following through this article: 
  • How to Save data using stored procedures in Sql server database and display the data from sql server database to repeater data control.
  • How to conditionally highlight table column background and text color in Repeater.
  • How to find HTML control inside Repeater e.g. we will find the table Column inside Repeater and assign color to it.


Description: Sometimes we want to highlight some data in repeater so that we can clearly differentiate some data against the large number of records being displayed in repeater. There may be multiple occasions where we need to change the row color of repeater to make it different and easily identifiable
For example: if we are displaying the details of all the students and we want to differentiate the students based on their gender i.e. By male or female then we can assign different colors to all the students based on their gender. I am going to implement this in this article.

Implementation:  Let's create a demo website to demonstrate the concept.
  • First of all create a DataBase in Sql server and name it e.g.  "DB_Student" and in this database create a table with the following Columns and Data type as shown below and name this table "Tbl_Student".


Column Name
Data Type
StudentId
Int(Primary Key. So set is identity=true)
StudentName
varchar(100)
Class
varchar(50)
Age
Int
Gender
varchar(50)
Address
varchar(500)

  • Create a stored procedure to save student details in sql server database table

 CREATE PROCEDURE SaveStudentDetails_SP
                @StudentName                               VARCHAR(100),
                @Class                                                 VARCHAR(50),
                @Age                                                    INT,
                @Gender                                             VARCHAR(10),
                @Address                                           VARCHAR(500)
AS
BEGIN
                INSERT INTO dbo.Tbl_Student(StudentName,Class,Age,Gender,Address)
                VALUES(@StudentName,@Class,@Age,@Gender,@Address)
END

  • Create another stored procedure to get student details to be filled in Repeater Data Control.

 CREATE PROCEDURE GetStudentDetails_SP               
AS
BEGIN
                SELECT * FROM dbo.Tbl_Student
END

  • Now let's connect our asp.net application with Sql Server database

So In the <configuration> tag of  web.config file create the connection string as:
  
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=DB_Student;Integrated Security=True"/>
  </connectionStrings>

Note:  Replace the Data Source and Initial Catalog as per your database settings.

In the <Form> tag of the asp.net design page (e.g. Default.aspx) design the page as:

<div>
<fieldset style="width:370px;">
    <legend>Highlight Repeater Column based on condition</legend>
    <table>
    <tr>
    <td>Student Name:</td>
    <td>
        <asp:TextBox ID="txtStuName" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Class:</td>
    <td>
        <asp:TextBox ID="txtClass" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Age:</td>
    <td>
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>       
    </tr>
    <tr>
    <td>Gender:</td>
    <td>
        <asp:RadioButtonList ID="rblGender" RepeatColumns="2" RepeatDirection="Horizontal" runat="server">
        <asp:ListItem>Male</asp:ListItem>
        <asp:ListItem>Female</asp:ListItem>
        </asp:RadioButtonList>
        </td>
    </tr>
    <tr>
    <td>Address:</td>
    <td>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
    <td>&nbsp;</td>
    <td>
        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
        <asp:Button ID="btnReset" runat="server" Text="Reset"
            onclick="btnReset_Click" />
        </td>
    </tr>

    <tr>
    <td colspan="2">
      <asp:Repeater ID="rptStudentDetails" runat="server"
            onitemdatabound="rptStudentDetails_ItemDataBound">
        <HeaderTemplate>
        <table border="1">
        <tr style="background-color:#fa7b16; color:#FFF; height:35px;" align="center">
        <th>Student Name</th>
        <th>Class</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Address</th>
        </tr>
        </HeaderTemplate>
        <ItemTemplate>
        <tr style="background-color:white;" align="center">
        <td><%#Eval("StudentName"%></td>
        <td><%#Eval("Class"%></td>
        <td><%#Eval("Age"%></td>

        <td id="tdID" runat="server"><%#Eval("Gender"%></td>

        <td><%#Eval("Address"%></td>
        </tr>
        </ItemTemplate>       
        <FooterTemplate>
        </table>
        </FooterTemplate>
        </asp:Repeater>  
    </td>
    </tr>
    </table>
    </fieldset>
    </div>

Note: You just need to give "id" and runat="server" to the "td" as highlighted above in yellow color. This way we can find the html cell i.e. "td" from the repeater in ItemDataBound event and assign color to it.

Asp.Net C# Section:
  • In code behind file (default.aspx.cs) write the code as;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls; 

public partial class default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindRepeater();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        try
        {
            cmd = new SqlCommand("SaveStudentDetails_SP", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StudentName", txtStuName.Text.Trim());
            cmd.Parameters.AddWithValue("@Class", txtClass.Text.Trim());
            cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim());
            if (rblGender.SelectedIndex == 0) //male
            {
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text);
            }
            else //Female
            {
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text);
            }
           
            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim());
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            Clear_Controls();
            BindRepeater();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Oops!! Error occured: " + ex.Message.ToString() + "');"true);
        }
        finally
        {
            cmd.Dispose();
            con.Close();
            con.Dispose();
        }
    }

    private void BindRepeater()
    {
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter();
        try
        {
            adp = new SqlDataAdapter("GetStudentDetails_SP", con);
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                rptStudentDetails.DataSource = dt;
                rptStudentDetails.DataBind();
            }
            else
            {
                rptStudentDetails.DataSource = null;
                rptStudentDetails.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Oops!! Error occured: " + ex.Message.ToString() + "');"true);
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Clear_Controls();
    }

       protected void rptStudentDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            HtmlTableCell td = (HtmlTableCell)e.Item.FindControl("tdID");
            DataRowView drv = e.Item.DataItem as DataRowView;
            string gen = Convert.ToString(drv["Gender"]);

            if (gen == "Male")
            {               
                td.Attributes.Add("style""background-color:#34d361;color:#FFFFFF;");
            }
            else
            {               
               td.Attributes.Add("style""background-color:#47ceef;color:#FFFFFF;");
            }
        }
    }
  
    private void Clear_Controls()
    {
        txtStuName.Text = string.Empty;
        txtClass.Text = string.Empty;
        txtAge.Text = string.Empty;
        rblGender.ClearSelection();
        txtAddress.Text = string.Empty;
        txtStuName.Focus();
    }
}

  
Asp.Net VB Section:
  • Design the page (default.aspx) as  in above Asp.net C#  section but replace the lines

<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
<asp:Button ID="btnReset" runat="server" Text="Reset" onclick="btnReset_Click" />
with the following lines
<asp:Button ID="btnSave" runat="server" Text="Save"/>
<asp:Button ID="btnReset" runat="server" Text="Reset" />

  •  In the code behind file(e.g. default.aspx.vb) write the code as:

 Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.UI.HtmlControls

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load
        If Not Page.IsPostBack Then
            BindRepeater()
        End If
    End Sub

    Protected Sub btnSave_Click(sender As Object, e As System.EventArgsHandles btnSave.Click
        Dim cmd As New SqlCommand()
        Try
            cmd = New SqlCommand("SaveStudentDetails_SP", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@StudentName", txtStuName.Text.Trim())
            cmd.Parameters.AddWithValue("@Class", txtClass.Text.Trim())
            cmd.Parameters.AddWithValue("@Age", txtAge.Text.Trim())
            If rblGender.SelectedIndex = 0 Then
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text)
            Else
                cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedItem.Text)
            End If

            cmd.Parameters.AddWithValue("@Address", txtAddress.Text.Trim())
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            Clear_Controls()
            BindRepeater()
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Oops!! Error occured: " & ex.Message.ToString() & "');"True)
        Finally
            cmd.Dispose()
            con.Close()
            con.Dispose()
        End Try
    End Sub

    Private Sub BindRepeater()
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter()
        Try
            adp = New SqlDataAdapter("GetStudentDetails_SP", con)
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                rptStudentDetails.DataSource = dt
                rptStudentDetails.DataBind()
            Else
                rptStudentDetails.DataSource = Nothing
                rptStudentDetails.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Oops!! Error occured: " & ex.Message.ToString() & "');"True)
        Finally
            con.Close()
            dt.Clear()
            dt.Dispose()
            adp.Dispose()
        End Try
    End Sub

Protected Sub rptStudentDetails_ItemDataBound(sender As Object, e As RepeaterItemEventArgs)
        If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then
            Dim td As HtmlTableCell = DirectCast(e.Item.FindControl("tdID"), HtmlTableCell)
            Dim drv As DataRowView = TryCast(e.Item.DataItem, DataRowView)
            Dim gen As String = Convert.ToString(drv("Gender"))

            If gen = "Male" Then
                td.Attributes.Add("style""background-color:#34d361;color:#FFFFFF;")
            Else
                td.Attributes.Add("style""background-color:#47ceef;color:#FFFFFF;")
            End If
        End If
    End Sub
  
    Protected Sub btnReset_Click(sender As Object, e As System.EventArgsHandles btnReset.Click
        Clear_Controls()
    End Sub

    Private Sub Clear_Controls()
        txtStuName.Text = String.Empty
        txtClass.Text = String.Empty
        txtAge.Text = String.Empty
        rblGender.ClearSelection()
        txtAddress.Text = String.Empty
        txtStuName.Focus()
    End Sub

Now over to you:
" I hope you have got the way to change the table cell color or we can say highlight repeater column conditionally  in Asp.Net and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..