I have a VS2010 ASP.Net webform that contains a GridView. This GridView has ShowHeaderWhenEmpty="True" so that the grid's headers display when the Grid's DataSource is empty.
Also. the GridView columns are TemplateFields. The first column has a new button in the HeaderTemplate. The New button Click event performs a GridView1.FooterRow.Visible = True so the user can insert a row into the table.
The problem is, when the DataSource is empty and the new button is clicked, I get this error: "Object reference not set to an instance of an object".
If the DataSource is NOT empty and the new button is clicked, everything works fine.
How can I show the GridView's FooterRow when the DataSource is empty?
--Update - This is the solution that I came up with.
private BindMyGrid()
{
bool isHideFirstRow = false;
if (_myEntity.Count > 0)
{
MyGrid.DataSource = _myEntity;
MyGrid.DataBind();
}
else
{
//Create an empty list and bind to that.
isHideFirstRow = true;
var list = new List<MyEntity> { new MyEntity { col1 = "", col2 = "", Col2 = "", IsEnabled = false } };
MyGrid.DataSource = list;
MyGrid.DataBind();
}
if (isHideFirstRow)
{
//Hide the first row if it's empty
MyGrid.Rows[0].Visible = false;
}
}