Displaying GridView Header When No Rows Are Returned
This question has been asked several times on www.asp.net forums so I am going to explain how you can do this. So, you have a GridView bound to some data source and as it so happens that the query you used to fetch the results from the source returns nothing. In that case you want to display the column names of the GridView. I am using DataSet as my container you can try it out with different containers.
private void BindData()
{
string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT CategoryID, CategoryName FROM Categories WHERE CategoryID = 100 ", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
if (ds.Tables[0].Rows.Count == 0)
{
AddDummyData(ds);
}
gv1.DataSource = ds;
gv1.DataBind();
}
private void AddDummyData(DataSet ds)
{
// Add a dummy row
DataTable dt = ds.Tables[0];
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
}
What I did is simply added a new dummy row. This row will force the GridView to be displayed and hence the column names will be displayed even though no data is returned.