ASP.NET 2.0 GridView Hack
Posted on March 29, 2007
Filed Under How-to, Programming
I’m new to ASP.NET 2.0 and like a lot of what I see. It looks as if the Microsoft team has really put their heads together to release a great product.
Since getting back to using a compiled language versus an interpreted language I’ve had to go back to using solid programming techniques - not a bad thing. C sharp has reared its head a few times. There are a ton of support forums on the net.
I do have one particular bone to pick though, and that’s the reason for this article.
The GridView is one of the web form controls available in Visual Studio 2005. It is a very powerful control; it produces a table layout of any SqlDataSource without the programmer having to spend a lot of time hand coding a database connection, fooling around with control loops and printing table cells. I can have customized headers and footers, customized templates depending on what type of mode I’m in. It truly is powerful tool indeed.
That is - as long as you have data being returned.
What happened to my wonderful headers and footers being displayed? It appears that I’m not the only one in ASP.NET land that has this beef. But I think I may have a solution, at least a start of a solution.
I have the following in my code behind file (sorry vb.net guys - this is c#):
int RowsInTable = 0;
SqlDataSource TestSource = SqlDataSource1;
DataView dv = (DataView)TestSource.Select(DataSourceSelectArguments.Empty);
foreach (DataRow dr in dv.Table.Rows)
{
RowsInTable++;
}
if (RowsInTable == 0)
{
DataSet ds = new DataSet();
ds.Tables.Add("Temp");
ds.Tables["Temp"].Columns.Add("Broker");
ds.Tables["Temp"].Columns.Add("Email");
ds.Tables["Temp"].Columns.Add("BrokerAssistantStatus", typeof(bool));
DataRow dr = ds.Tables["Temp"].NewRow();
dr["Broker"] = " ";
dr["Email"] = " ";
dr["BrokerAssistantStatus"] = 0;
ds.Tables["Temp"].Rows.Add(dr);
GridView2.DataSource = ds;
GridView2.DataSourceID = "";
GridView2.DataBind();
}
else
{
GridView2.DataSourceID = "SqlDataSource1";
GridView2.DataSource = null;
GridView2.DataBind();
}
- Make a copy of my data source.
- Create a new DataView based on that copy.
- Count the number of rows in the table.
- If the number is zero let the fun begin.
- Create a new DataSet and add a table to it.
- Add the same number of columns with matching names that your GridView is expecting to bind to. Be mindful to add a typeof() if needed. I got tripped up on the bool for a bit.
- Create a new DataRow.
- Set the data row variables, make sure the names match those of your GridView.
- Add the row to the new DataSet table.
- Set the GridView DataSource property to the DataSet created earlier. Make sure to set the DataSourceID to null or “” since you cant have both the Source and SourceID defined.
- Finally DataBind to the GridView.
I have my header and footer displayed even though there is “no data” returned from the SqlDataSource.