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

Introduction: In this article i will explain how to bind GridView with header i.e. with Columns names and with custom message like "No Data Found" etc when no data present in DataSet in Asp.net.
In previous articles i explained How to bind empty GridView with header and custom message when no data present in Datatable in Asp.net  and How to bind gridview using SqlDataAdapter, SqlCommand, DataSet and Stored procedure in Asp.net  and  How to pass parameter to stored procedure using SqlDataAdapter and check login in asp.net.

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);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            MyGridView.DataSource = ds;
            MyGridView.DataBind();
        }
        else
        {
            BingEmpyGridViewWithHeader(MyGridView, ds, "No data found");
        }
    }
    protected void BingEmpyGridViewWithHeader(GridView grd, DataSet ds, String msg)
    {
        try
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                //Add a blank row to the dataset
                ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                //Bind the DataSet to the GridView
                grd.DataSource = ds;
                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  
 Add following code in the code behind file(.aspx.vb)  
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 ds As New DataSet()
        adp.Fill(ds)
        If ds.Tables(0).Rows.Count > 0 Then
            MyGridView.DataSource = ds
            MyGridView.DataBind()
        Else
            BingEmpyGridViewWithHeader(MyGridView, ds, "No data found")
        End If
    End Sub

    Protected Sub BingEmpyGridViewWithHeader(grd As GridView, ds As DataSet, msg As [String])
        Try
            If ds.Tables(0).Rows.Count = 0 Then
                'Add a blank row to the dataset
                ds.Tables(0).Rows.Add(ds.Tables(0).NewRow())
                'Bind the DataSet to the GridView
                grd.DataSource = ds
                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 »

1 comments:

Click here for comments
Anonymous
admin
October 11, 2013 ×

No words to thanks
Very ... useful

Congrats bro Anonymous you got PERTAMAX...! hehehehe...
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..