Welcome to AspAdvice Sign in | Join | Help

AzamSharp

Some day I will know everything I hope that day never comes

Syndication

Tags

Navigation

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.

Published Monday, January 01, 2007 8:00 PM by azamsharp

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Displaying GridView Header When No Rows Are Returned @ Thursday, February 01, 2007 3:05 PM

I did that in 1.1 Try EmptyDataText="No Data Found"

kwells

# re: Displaying GridView Header When No Rows Are Returned @ Thursday, February 01, 2007 10:01 PM

The EmptyDataText will only work if there are no rows returned for the GridView. In this case the header will not be displayed at all.

azamsharp

# re: Displaying GridView Header When No Rows Are Returned @ Tuesday, February 06, 2007 5:57 PM

How do you retrieve the dataset from a sqldatasource that is declared in the aspx page and make it rebind to the one with the dummy record ?

hercules

# re: Displaying GridView Header When No Rows Are Returned @ Tuesday, February 06, 2007 11:00 PM

The DataSet is not retrieved from the SqlDataSource. The DataSet was populated using the SqlDataAdapter.

azamsharp

# re: Displaying GridView Header When No Rows Are Returned @ Friday, October 12, 2007 12:20 PM

This worked great for me; I'm using ObjectDataSource; but there's one small problem which is that I have a couple of hyperlink columns, and they still display on the empty row. I wonder if there's a way to make them go away if the row is empty.

dave

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below