Issue
I'm trying to display a table with 8 rows and 8 columns, each cell is an input that maps to a value in a corresponding array. Upon first displaying the page, the correct values are in the cells.
When I type in a number in the input cell in order to update the value in the actual array, the row and col values are 8, instead of the appropriate values for that cell.
Here's the relevant section of the .razor file:
<table class="table">
<thead>
<!--
<tr>
<th>Runs with</th>
@foreach (var dog in dogList)
{
<th>@dog.name</th>
}
</tr>
-->
</thead>
<tbody>
<!-- The header, but not bold -->
<tr>
<td style="width:120px;">Runs with ↗️ </td>
@foreach(Dog dog in dogList)
{
<td style="width:120px;">@dog.name</td>
}
</tr>
@for(var row = 0; row<dogList.Count; row++)
{
<tr>
<td style="width:120px;">@dogList[row].name</td>
@for (var col = 0; col<dogList.Count; col++)
{
<td style="width:120px;">
<input type="number"
value="@dogSpeed[row][col]"
@oninput="@(e => {this.updateDogSpeed(row, col, e);})"
/>
</td>
<!-- @oninput="@(e => {@dogSpeed[@row][@col] = double.Parse(e.Value.ToString());})" -->
}
</tr>
}
</tbody>
</table>
@code {
public void updateDogSpeed(int row, int col, ChangeEventArgs e)
{
//dogSpeed[row][col] = double.Parse(e.Value.ToString());
Console.WriteLine($"row={row}, col={col}, e.Value={e.Value}");
//Console.WriteLine($"New value for dog speed[{row}][{col}]: {dogSpeed[row][col]} (e.Value={e.Value}");
}
}
The console output shows row=8, col=8, e.Value=(whatever new value I type in, good)) This gets printed out regardless which input cell I update.
What magic incantation do I need to get the correct row and col values to be passed in?
I'd like to do this the "proper" way, without resorting to JavaScript. I'm ok with updating the dogSpeed array inside the for loop directly, or doing it by calling updateDogSpeed(row, col, newValue)
Solution
Use local variables within the inner loop block to remember the row and column associated with that iteration.
@for(var row = 0; row<dogList.Count; row++)
{
<tr>
<td style="width:120px;">@dogList[row].name</td>
@for (var col = 0; col<dogList.Count; col++)
{
int currentRow = row;
int currentCol = col;
<td style="width:120px;">
<input type="number"
value="@dogSpeed[row][col]"
@oninput="@(e => {this.updateDogSpeed(currentRow, currentCol, e);})"
/>
</td>
}
</tr>
}
There will be a new set of these variables for each loop iteration while the actual loop variables change their value.
See Captured variable in a loop in C# for details.
Answered By - NineBerry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.