I have a small problem with my table, the buttons and the onclick work fine, but the paramter I want to pass with the click doesn't work the way I expect it to.
here's the code.
<table class="table-spaced table-responsive">
<thead>
<tr>
<th />
@for (int i = 1; i <= Plate.PlateType.NumberOfColumns; i++)
{
<th class="cell_head">@i</th>
}
</tr>
</thead>
<tbody>
@for (int y = 0; y < Plate.PlateType.NumberOfRows; y++)
{
<tr>
<td style="vertical-align:central">
@Helper.RowLetters[y]
</td>
@for (int x = 1; x <= Plate.PlateType.NumberOfColumns; x++, Position = string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x))
{
if (Plate.Compounds.ContainsKey(string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x)))
{
----> <td class="compound"><button type="button" class="compound" @onclick="() => PlateGridClick(Position)" itemprop="@string.Format("{0:c}{1:d2}", Helper.RowLetters[y], x))"/></td>
}
else
{
<td class="no_compound" />
}
}
</tr>
}
</tbody>
</table>
the table is for example P24 in size, Position is always P25 regardless of which button I press, I want the value of Position when that particular cell is created, but Position seems to be set when I click the button, when the whole table is already created and the coordinates have reached the end.
is there a way to achieve the same functionality regarding the click event in blazor, but that stores the parameter in the button rather then fetching the Position parameter's current value when clicking?
I believe that this is the result of using a for loop.
Try this: define a local variable in your for loop and assign the value of the local variable to the necessary code.
Sample code to clarify what I mean:
This loop creates 10 buttton elements with the value 10 passed to the ShowPosition method. The value 10 is passed to the ShowPosition method no matter what button you click. 10 is the value of i when the for loop ends. This is the way not to do it
@for (int i = 0; i < 10; i++)
{
<button type="button" @onclick="() => ShowPosition(i)">Click</button>
}
In order to do it right you should create a local variable like the following
@for (int i = 0; i < 10; i++)
{
var local_i = i;
<button type="button" @onclick="() => ShowPosition(local_i)">Click</button>
}
Now, whenever you click a button control, you get the correct value.
Please, search for a complete answer with explanation how lambada methods behave with the user Isaac . That's me.
Hope this helps...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With