How to bind empty GridView with header and custom message when no data present in Datatable in Asp.net

How to bind empty gridview with header and message in asp.netIntroductionIn this article i will explain how to bind GridView control with header i.e. with Column names and Custom message like "No Data Found" etc.It become necessary to bind empty gridview where there is no data in data source e.g Datatable.

In previous articles i explained How to Upload and store image in binary format in Sql server database and retrieve, bind to Gridview and Bind,upload,download,delete image files from the GridView and Change GridView cell background color based on condition and Upload and create Zip file in asp.net and  Bind gridview using SqlDataAdapter, SqlCommand, DataTable and Stored procedure and  Pass parameter to stored procedure using SqlDataAdapter and check login and Highlight gridview row on mouse over using CSS

Description: Sometimes we want to show the header of the gridview i.e. header with column names even when there is no data to fill in gridview. So i have created a sample web page to implement this functionality. It will bind the records in gridview if there are records in the database and it will show empty gridview with message as shown in image above.

Implementation: Let's create a sample web page to demonstrate the concept.

First of all create a database e.g. "EmpDb" and in that create a table with the columns as shown below and name it "employee":

Column Name
Data Type
EmpId
Int(Primary key so set Is Idenetity=True)
EmpName
varchar(50)
Salary
decimal(18, 2)
Dept
varchar(50)

  • In the web.config file create the connection string as:

<connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=EmpDb;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source as per your application

  • In the design page(.aspx) place a GridView control as
        <fieldset style="width:175px">
    <legend>GridView with empty data</legend>
    <asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="False">
                    <Columns>
                         <asp:BoundField DataField="EmpName" HeaderText="Name" />
                         <asp:BoundField DataField="Dept" HeaderText="Department" />
                         <asp:BoundField DataField="Salary" HeaderText="Salary" />
                    </Columns>
         </asp:GridView>
    </fieldset>
  • Add following code in the code behind file(.aspx.cs)

C#.Net Code to bind empty GridView with header and custom message

First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
then write code as:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

     
private void BindGrid()
    {
        SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlDataAdapter adp=new SqlDataAdapter("select * from employee",con);
        DataTable dt=new DataTable();
        adp.Fill(dt);
        if (dt.Rows.Count>0 )
        {
            MyGridView.DataSource = dt;
            MyGridView.DataBind();
        }
        else
        {
            BingEmpyGridViewWithHeader(MyGridView, dt, "No data found");
        }
    }

    protected void BingEmpyGridViewWithHeader(GridView grd, DataTable dt,String msg)
{
            try
    {
                        if (dt.Rows.Count == 0) {
                                    //Add a blank row to the datatable
                                    dt.Rows.Add(dt.NewRow());
                                    //Bind the DataTable to the GridView
                                    grd.DataSource = dt;
                                    grd.DataBind();
                                    //Get the number of columns to know what the Column Span should be
                                    int columnCount = grd.Rows[0].Cells.Count;
                                    //Call the clear method to clear out any controls that you use in the columns.  E.g If you are using dropdown list etc. in any of the column then it is necessary.
                                    grd.Rows[0].Cells.Clear();
                                    grd.Rows[0].Cells.Add(new TableCell());
                                    grd.Rows[0].Cells[0].ColumnSpan = columnCount;
                                    grd.Rows[0].Cells[0].Text = "<font color=Red><b><center>"+ msg +"</center></b></font>";
                        }
            }
    catch (Exception ex)
    {
                        //Do your exception handling here
            }
}

VB.Net Code to bind empty GridView with header and custom message

First import the following namespaces

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration 

then write code as:
Protected Sub Page_Load(sender As Object, e As EventArgs)
               If Not IsPostBack Then
                               BindGrid()
               End If
End Sub

Private Sub BindGrid()
               Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
               Dim adp As New SqlDataAdapter("select * from employee", con)
               Dim dt As New DataTable()
               adp.Fill(dt)
               If dt.Rows.Count > 0 Then
                               MyGridView.DataSource = dt
                               MyGridView.DataBind()
               Else
                               BingEmpyGridViewWithHeader(MyGridView, dt, "No data found")
               End If
End Sub

Protected Sub BingEmpyGridViewWithHeader(grd As GridView, dt As DataTable, msg As [String])
               Try
                               If dt.Rows.Count = 0 Then
                                              'Add a blank row to the datatable
                                              dt.Rows.Add(dt.NewRow())
                                              'Bind the DatTable to the GridView
                                              grd.DataSource = dt
                                              grd.DataBind()
                                              'Get the number of columns to know what the Column Span should be
                                              Dim columnCount As Integer = grd.Rows(0).Cells.Count
                                              'Call the clear method to clear out any controls that you use in the columns.  E.g If you are using dropdown list etc. in any of the column then it is necessary.
                                              grd.Rows(0).Cells.Clear()
                                              grd.Rows(0).Cells.Add(New TableCell())
                                              grd.Rows(0).Cells(0).ColumnSpan = columnCount

                                              grd.Rows(0).Cells(0).Text = "<font color=Red><b><center>" & Convert.ToString(msg) & "</center></b></font>"
                               End If
                                              'Do your exception handling here
               Catch ex As Exception
               End Try
End Sub

Now over to you:
" I hope you have got How to bind empty header in gridview when there is no data to fill in gridview  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..