Removing item from List messes up rest of the items in the list

Viewed 1543

I have an html table in blazor that fills up looping over a list (columns reduced to show relevant code)

@foreach (var line in lines)
     {@{ var linenumber = lines.IndexOf(line)}
             <td>
                 <DDItems @bind-Binder="line.item"></DDItems>
             </td>
              <td>
                 <button type="button" @onclick="@(() => removeRow(linenumber))">Remove</button>
             </td>
     }

 @Code{
private List<TransactionSALine> lines = new List<TransactionSALine>();
   private async Task removeRow(int linenumber)
 {
     lines = lines.Where(u => lines.IndexOf(u) != linenumber).ToList());

 }
}

When I remove one of the rows from the table, item selected in other rows gets changed.

  • I have tried to use an array instead of the list but that didn't help.
  • Tried to change the removerow() method using Linq and RemoveAt(). Doesn't change the result.

Before removing the row with Product "pencil": 1

After removing the product "pencil": 2

1 Answers

Your snippet does not include the <tr> element. It has to be in there, first level inside the foreach(). You can help the rendering by specifying a key:

@foreach (var line in lines)
{
   <tr @key="@line">
   ... 
   </tr>
}

I think this takes care of the disappearing Pen item, try it.

On a side note, you can simplify the removal a lot:

  @onclick="@(() => lines.Remove(line))">


// private async Task removeRow(int linenumber)
// {
//     lines = lines.Where(u => lines.IndexOf(u) != linenumber).ToList());
// }
Related