在 Gridview 中显示 FooterRow
我有一个包含 GridView 的 VS2010 ASP.Net Web 表单。此 GridView 具有 ShowHeaderWhenEmpty="True" ,以便当网格的数据源为空时显示网格的标题。
还。 GridView 列是 TemplateFields。第一列在 HeaderTemplate 中有一个新按钮。 “新建”按钮 Click 事件执行 GridView1.FooterRow.Visible = True,以便用户可以在表中插入一行。
问题是,当数据源为空并且单击新按钮时,我收到此错误:“对象引用未设置为对象的实例”。
如果数据源不为空并且单击了新按钮,则一切正常。
当数据源为空时,如何显示 GridView 的 FooterRow?
--更新-这是我想出的解决方案。
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;
}
}
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以这样做......
一个更优雅的解决方案,在不篡改数据源的情况下,创建一个扩展 GridView 的自定义控件并覆盖 CreateChildControls,如下所示
注意:这是一个关于如何显示的示例当网格视图的数据源为空时,页脚和页眉也会显示......
ShowWhenEmpty 是一个简单的属性,设置 true 可以在空时显示页眉和页脚:
you can do like this....
a more elegant solution, without tampering with the datasource, is creating a custom control that extends GridView and overriding CreateChildControls like so
NOTE: This is an example on how to show footer and header also when the datasource of grid view is empty.......
ShowWhenEmpty is a simple property that you set true to display headers and footers when empty: