Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

asp.net

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

like image 616
ram Avatar asked Nov 30 '25 19:11

ram


1 Answers

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: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

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:

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.

like image 89
Karl Anderson Avatar answered Dec 03 '25 10:12

Karl Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!