Breaking News

Editors Picks

Thursday, April 7, 2011

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 Users WHERE UserID = @UserID";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            sqlCmd.Parameters.AddWithValue("@UserID", userID);
            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)
        {
              
        }
        finally
        {
            connection.Close();
        }
}

Read more ...

Contact Us

Name

Email *

Message *