And how to add a new row in the gridview at the run time by simply pressing the tab key?
5 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.
Comments
GridView1.DataSourceID = String.Empty; GridView1.DataBind();