Search
Close this search box.

Tip/Trick: Show Header and Footer of GridView when no Data returned.

This example demonstrates on how to show the Header and Footer of GridView when no data returned from the DataSet or DataTable. 

The trick here is to add a new blank row to the DataTable that you used as your DataSource if there was no data returned in your query.

Here’s the method for showing the Header and Footer of GridView when no data returned in the query.

private
void ShowNoResultFound(DataTable source, GridView gv)

{
  source.Rows.Add(source.NewRow());  // create a new blank row to the DataTable

  // Bind the DataTable which contain a blank row to the GridView

  gv.DataSource = source;

  gv.DataBind();

  // Get the total number of columns in the GridView to know what the Column
  // Span should be

  int columnsCount = gv.Columns.Count;

  gv.Rows[0].Cells.Clear();  // clear all the cells in the row

  gv.Rows[0].Cells.Add(new TableCell());  // add a new blank cell

  gv.Rows[0].Cells[0].ColumnSpan =
      columnsCount;  // set the column span to the new added cell

  // You can set the styles here

  gv.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;

  gv.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;

  gv.Rows[0].Cells[0].Font.Bold = true;

  // set No Results found to the new added cell

  gv.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
}

As you can see, the method above takes two paramaters, first is the DataTable that you used as the DataSource, second is the ID of your GridView.

All you need to do is Call the method ShowNoResultFound() when your DataSource ( the DataTable) returns nothing. See this example below

private
void BindGridView()

{
  DataTable dt = new DataTable(string user);

  SqlConnection connection = new SqlConnection(GetConnectionString());

  try

  {
    connection.Open();

    string sqlStatement = "SELECT* FROM Orders WHERE UserID = @User";

    SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);

    sqlCmd.Parameters.AddWithValue("@User", user);

    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    sqlDa.Fill(dt);

    if (dt.Rows.Count > 0)  // Check if DataTable returns data

    {
      GridView1.DataSource = dt;

      GridView1.DataBind();
    }

    Else  // else if no data returned from the DataTable then

    {  // call the method ShowNoResultFound()

      ShowNoResultFound(dt, GridView1);
    }

  }

  catch (System.Data.SqlClient.SqlException ex)

  {
    string msg = "Fetch Error:";

    msg += ex.Message;

    throw new Exception(msg);

  }

  finally

  {
    connection.Close();
  }
}

Here’s the page out below:

This article is part of the GWB Archives. Original Author: Vinz’s Blog

Related Posts