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

12.5k views Asked by At

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

5

There are 5 answers

0
Habib On BEST 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();
0
Tomáš Novák On

Something like that, its working...

private void ClearDataRows(Table table)
{
      if (table.Rows.Count <= 1) return;

      var rowCount = table.Rows.Count;
      for (var i = 1; i < rowCount; i++)
          table.Rows.RemoveAt(1);
}

Be sure you start at 1 (index), because 0 is table header. Be sure in for loop you have "RemoveAt(1)"...

1
user3158212 On
while (MyTable.Rows.Count > 1) MyTable.Rows.RemoveAt(1);
1
Colin Gardner On

Why not make it a bit more generalised and create an extension methods something like the following:

    /// <summary>
    /// Clears rows from the TableRowCollection starting from the specified Start index
    /// </summary>
    /// <param name="Rows">The TableRowCollection</param>
    /// <param name="Start">Start Index</param>
    public static void ClearFrom(this WebControls.TableRowCollection Rows, int Start)
    {
        if (Start == 0)
        {
            Rows.Clear();
        }
        else if (Start >= Rows.Count)
        {
            return;
        }
        else
        {
            for (int i = Start; i < Rows.Count; i++)
            {
                Rows.RemoveAt(i);
            }
        }
    }

Now you can clear rows from any start index, not just 1.

Call as follows:

MyTable.Rows.ClearFrom(1);
0
László Koller On

To remove a row from a row collection, use (and be sure to start your loop at 1, not 0):

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

Alternatively, you could use:

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