skip to Main Content

I have a standard Blazor app where I dynamically create a table and want to be able to identify each table entry by a unique identifier.

Currently I have each <td> element be assigned the counter value in my for loop like so:

for (var i=0; i < 7; i++)
{
  <td id=@i @onlick="() => SelectEntry()">@i</td>
}

I want to be able to pass the id value to the onclick method so I know which table entry was clicked on but am unsure how.

2

Answers


  1. It is important that you assign your value from i to a new variable, otherwise you would always pass the last value of i into the function.

    What you can do would be this:

    for (var i = 0; i < 7; i++)
    {
      var myValue = i;
      <td id="@myValue" @onlick="() => SelectEntry(myValue)">@myValue</td>
    }
    
    Login or Signup to reply.
  2. You current method will not produce unique ids: you assign the same id to cells in each row.

    Here’s some code that will make each cell unique. It uses a guid to identify the table and then Rx:Cx to identify the cell.

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <table class="table">
        @for (var row = 1; row < 10; row++)
        {
            <tr>
                @for (var col = 1; col < 5; col++)
                {
                    var id = $"R{row}:C{col}";
                    var uid = $"{_tableId}-R{row}:C{col}";
                    <td class="@this.CellCss(uid)" id="@uid" @onclick="() => this.OnCellSelected(uid)">@id</td>
                }
            </tr>
        }
    </table>
    
    <div class="bg-dark text-white m-2 p-2">
        <pre>Selected Cell: @_selectedCell</pre>
    </div>
    
    @code {
        private string? _selectedCell;
    
        private string _tableId = Guid.NewGuid().ToString();
    
        private string CellCss(string value)
            => value.Equals(_selectedCell)
                ? "bg-dark text-white"
                : "";
    
        private void OnCellSelected(string? value)
            => _selectedCell = value;
    }
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search