C# 当表格仅包含标题并且表格中没有插入行时,如何在asp.net中显示空的gridview?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17067223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:30:06  来源:igfitidea点击:

How to display a empty gridview in asp.net when the table contains only headers and there is no row inserted on the table?

c#asp.net.net

提问by ram

And how to add a new row in the gridview at the run time by simply pressing the tab key?

以及如何在运行时通过简单地按 Tab 键在 gridview 中添加新行?

回答by kman

if you're using .NET 4.0 or later, there's a property you can set on the GridView - ShowHeaderWhenEmpty. Just make sure you're actually bound to an empty list.

如果您使用 .NET 4.0 或更高版本,则可以在 GridView 上设置一个属性 - ShowHeaderWhenEmpty。只要确保你确实绑定到一个空列表。

回答by Karl Anderson

If you are using ASP.NET 4.0 or later, then you can use the ShowHeaderWhenEmpty property and set it to true, like this:

如果您使用的是 ASP.NET 4.0 或更高版本,则可以使用 ShowHeaderWhenEmpty 属性并将其设置为 true,如下所示:

<asp:GridView runat="server" id="gv" ShowHeaderWhenEmpty="true">
    // Normal grid view logic would go here
</asp:GridView>

Here is a link to the MSDN documentation for ShowHeaderWhenEmpty

这是ShowHeaderWhenEmpty的 MSDN 文档的链接

If you are using ASP.NET 3.5 or earlier, then you have to use an "empty row" trick to make the headers show in your GridView even if there is no data, like this:

如果您使用的是 ASP.NET 3.5 或更早版本,那么即使没有数据,您也必须使用“空行”技巧使标题显示在您的 GridView 中,如下所示:

List<string> rows = new List<string>(
new string[] { "Row 1", "Row 2", "Row 3" });

rows.Clear();
if (rows.Count > 0)
{
    gv.DataSource = rows;
    gv.DataBind();
}
else
{
    rows.Add("");
    gv.DataSource = rows;
    gv.DataBind();
    gv.Rows[0].Visible = false;
}

Note: In this contrived example, the else will always execute as we are clearing the list before checking the amount of items in the list, but you should get the idea here; add an "empty" row, bind the grid view and then hide the row you just added. The initial bind of an "empty" row will make the headers show and then the row being hidden will make it appear like an empty grid view.

注意:在这个人为的例子中,else 将始终执行,因为我们在检查列表中的项目数量之前清除列表,但您应该在这里了解这个想法;添加一个“空”行,绑定网格视图,然后隐藏您刚刚添加的行。“空”行的初始绑定将使标题显示,然后隐藏的行将使其看起来像一个空的网格视图。

回答by Yemol

If you are using table as data source. you only need to create a new row with blank value.

如果您使用表作为数据源。您只需要创建一个具有空白值的新行。

table.Rows.Add(table.NewRow());

回答by Deep

GridView1.DataSourceID = null;
GridView1.DataBind();

Make sure it's DataSourceIDand not DataSource.

确保它是DataSourceID而不是 DataSource。