Home > ASP.Net > Show Header and Footer of GridView when no Data returned

Show Header and Footer of GridView when no Data returned


Hi

try this example to Show Header and Footer of GridView when no Data returned:

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!";
    }

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

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: