user3432257 user3432257 - 29 days ago 11
ASP.NET (C#) Question

asp.net how to remove all the rows from a table except the first one

In the past i was using this

DateBookingTable.Rows.Clear();


To remove all the rows.

Now I want to remove all the rows except the first one.

why I want that?



because when I remove all the rows, the
th
is removed, i don't want that. i want to remove all the data. not the
th


this is what i don't want to remove

<tr><th>ID</th><th>PlanTime</th></tr>


what I have tried



I make this loop:

for (int i = 0; i < DateBookingTable.Rows.Count; i++) {
if (i >0){
//here what should I do
}
}


but I didn't know how to remove that row in the looop

Answer

In your loop you can use

DateBookingTable.Rows.RemoveAt(i);

You can modify your loop to start with 1 instead of 0 and thus avoiding checking it against 0 in each iteration.

for (int i = 1; i < DateBookingTable.Rows.Count; i++)
{
    DateBookingTable.Rows.RemoveAt(i);
}

if you want to remove rows from client side using jQuery then you can do:

 $('#yourtableID').find("tr:gt(0)").remove();