3

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

0

5 Answers 5

11

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Make sure it's DataSourceID and not DataSource.

Comments

0

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.

Comments

0

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

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

Comments

0

GridView1.DataSourceID = String.Empty; GridView1.DataBind();

1 Comment

please, add more details in your answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.