1

I'm a beginner in both c# and Blazor, so my question may seem trivial.

I have a table with one row having input components.

<table>
    <tr>
        <th>X2</th>
        @foreach (var item in Data)
        {
            <td><input type="number" min="0" max="360" step="1" @onchange="ItemChanged"></td>
        }
    </tr>
</table>

In the code I have a list of double as shown below. I also have an ItemChanged function which is triggered when the user changes the value of an input

@code {
    public List<double> Data = new List<double>{1.2, 0.5, 0.8, 1.4};
    
    public void ItemChanged(ChangeEventArgs args)
    {
        Data[1] = Convert.ToDouble(args.Value);
    }

The issue I have is to get the index of the cell containing the input who got the value changed. So I could change the Data[1] to Data[index] in my code.

Thank you

Bert54
  • 37
  • 5
  • While @maciek answer below is correct, is this a case of "Primitive Obsession"? The doubles represent something. Create an object that defines what you are representing. You can then use `foreach` on the list of the objects. – MrC aka Shaun Curtis Dec 11 '22 at 23:54

1 Answers1

2

What I would do is I would change to:

<table>
    <tr>
        <th>X2</th>
        @for(int i=0; i < Data.Count(); i++)
        { 
            int b=i;
            <td><input type="number" min="0" max="360" step="1" @onchange="args =>ItemChanged(args,b)"></td>
        }
    </tr>
</table>

@indx

And the function:

@code {
    public List<double> Data = new List<double>{1.2, 0.5, 0.8, 1.4};
    
    public int indx = 0;

    public void ItemChanged(ChangeEventArgs args, int index)
    {
        Data[index] = Convert.ToDouble(args.Value);
        indx = index;
    }
}

https://blazorrepl.telerik.com/GGFGFPvX06jDD4rL39

maciek
  • 724
  • 2
  • 4
  • 16