Show the gridview header and footer when there is no records in database table
Show gridview header and footer when there is no records in table
Purpose:
How to show the gridview header and footer when there is no records in database table
Connection Object...
SqlConnection con = new SqlConnection("Data Source=SUSANT\\SQLEXPRESS ;Initial Catalog=AG; Integrated Security=True;");
DataTable dt = new DataTable();
//PageLoad Event..
protected void Page_Load(object sender, EventArgs e)
{
show_data();
// show_data() method to select all the values from database
public void show_data()
{
try
{
if (con.State==ConnectionState.Open)
{
con.Close();
}
con.Open();
DataSet ds = new DataSet();
string str = "select * from student";
SqlDataAdapter da = new SqlDataAdapter(str, con);
da.Fill(ds, "temp");
da.Fill(dt);
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
else
{
ShowNoResultFound(dt,GridView1);
}
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
//ShowNoResultFound() it will check if no record then it will create one error message...
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!";
}
Reference: http://susantown.blogspot.com/2009/07/purpose-how-to-show-gridview-header-and.html
It is a nice article its working properly in asp.net