Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Wednesday, 4 February 2015


Introduction: 

In this article we will show GridView control with header in case of empty Datatable.


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. In this example we will bind the datatable  with gridview if there is no records in the database and it will show empty gridview with message “No data Found”.

Implementation:
First of all create a database e.g. "test" and in that create a table with the columns as shown below and name it "employee":
Column Name
Data Type
empid
Int(Primary key)
empname
varchar(50)
salary
decimal(18, 2)


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

<connectionStrings>
    <add name="conStr" connectionString="Data Source=localhost;Initial Catalog=test;IntegratedSecurity=True"/>
  </connectionStrings>

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="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)
    {
                        // Handle exception 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

0 comments:

Post a Comment