Show Empty template in Asp.net repeater with header and No records found message

Bind empty asp.net repeater with message when no data is present
Introduction: In this article i am going to share the code to Bind/Show empty template in Repeater with "No records available to display" message when there is no data available in table to display in repeater data control in asp.net using both C# and VB languages.

Description: Basically you will learn the following through this article: 
  • How to bind the data from sql server database table to repeater data control.
  • How to display message in repeater with just header when no row is present
  • How to find HTML control inside Repeater's Footer e.g. we will find the div placed inside Repeater and access its "visible" property to make it appear when no data is available to bind in repeater.  
   
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 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:305px;">
    <legend>Show empty data in Repeater with message</legend>
    <table>
    <tr>
    <td>
      <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><%#Eval("Gender") %></td>
        <td><%#Eval("Address") %></td>
        </tr>
        </ItemTemplate>      
        <FooterTemplate>
        </table>
        <div id="dvNoRecords" runat="server" visible="false" style="padding:20px 20px; text-align:center; color:Red;">
        No records to display.
        </div>
        </FooterTemplate>
        </asp:Repeater> 
    </td>
    </tr>
    </table>
    </fieldset>
    </div>

Notice the yellow highlighted block above where i have added a div having message "No records to display" in the repeater's Footer and set its visible property to false. Also i have assigned id and  runat="server" to div so that we can access it from Repeater's ItemDataBound event and if there are no records to display in the repeater then we will show this div having "No records to display" message.

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();
        }
    }

  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);
            rptStudentDetails.DataSource = dt;
            rptStudentDetails.DataBind();
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured: " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            dt.Clear();
            dt.Dispose();
            adp.Dispose();
        }
    }
    protected void rptStudentDetails_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (rptStudentDetails.Items.Count < 1)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                HtmlGenericControl dvNoRec = e.Item.FindControl("dvNoRecords") as HtmlGenericControl;
                if (dvNoRec != null)
                {
                    dvNoRec.Visible = true;
                }
            }
        }
    }
}

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

<asp:Repeater ID="rptStudentDetails" runat="server"
            onitemdatabound="rptStudentDetails_ItemDataBound">
with following line:
<asp:Repeater ID="rptStudentDetails" runat="server">
  
  • 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.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindRepeater()
        End If
    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)
            rptStudentDetails.DataSource = dt
            rptStudentDetails.DataBind()
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[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 System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptStudentDetails.ItemDataBound
        If rptStudentDetails.Items.Count < 1 Then
            If e.Item.ItemType = ListItemType.Footer Then
                Dim dvNoRec As HtmlGenericControl = TryCast(e.Item.FindControl("dvNoRecords"), HtmlGenericControl)
                If dvNoRec IsNot Nothing Then
                    dvNoRec.Visible = True
                End If
            End If
        End If
    End Sub
End Class


Now over to you:
" I hope you have got the way to bind empty template in repeater with custom message  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 »

3 comments

Click here for comments
Anonymous
admin
February 19, 2015 ×

Hi, It helped me a lot at correct time..thank you for your blog..its really awesome

Reply
avatar
February 20, 2015 ×

Thanks for your valuable feedback..:)

Reply
avatar
Unknown
admin
May 26, 2017 ×

Great Sir

Reply
avatar

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..