IgbGrid を使用して、コードビハインドで選択した行を更新する方法について解説します。

IgbGrid の設定

まず、IgbGrid を使用してデータを表示する準備をします。@ref ディレクティブを使って、IgbGrid を参照できるように設定します。
以下のコード例では、_people リストを IgbGrid にバインドし、Name, JobTitle の各列を表示しています。

<IgbGrid Data="_people"
         @ref="gridRef"
         PrimaryKey="@nameof(Person.Id)"
         AutoGenerate="false"
         RowSelection="GridSelectionMode.Single"
         CellSelection="GridSelectionMode.None"
         RowSelectionChanging="OnRowSelection">
    <IgbColumn Field="@nameof(Person.Id)" Header="ID" Hidden="true"></IgbColumn>
    <IgbColumn Field="@nameof(Person.Name)" Header="Name"></IgbColumn>
    <IgbColumn Field="@nameof(Person.JobTitle)" Header="Job Title"></IgbColumn>
</IgbGrid>

UpdateRowAsync メソッドの使用

次に、入力したデータを基に、行の更新を処理するためのメソッドを実装します。
UpdateRowAsyncメソッドを使用して、選択された行の Name と JobTitle を更新します。

private async Task OnUpdatePerson()
{
    if (_selectedPerson is null || gridRef is null) return;
    _selectedPerson.Name = _selectedPersonName;
    _selectedPerson.JobTitle = _selectedPersonJobTitle;

    var updateValues = new Dictionary<string, object>
    {
        { nameof(Person.Id), _selectedPerson.Id },
        { nameof(Person.Name), _selectedPerson.Name ?? string.Empty },
        { nameof(Person.JobTitle), _selectedPerson.JobTitle ?? string.Empty }
    };
    await gridRef.UpdateRowAsync(updateValues, _selectedPerson.Id);
}

UpdateRowAsyncメソッドには、更新する行の新しいデータと ID を渡します。このメソッドにより、選択された行の情報が即座に反映されます。

今回の例ではデータを更新するためのフォームを作成します。このフォームには、Name と JobTitle の入力フィールドを配置し、フォームの入力値は @bind-Value を使用してコードビハインドの変数にバインドします。「Update」ボタンをクリックすると、OnUpdatePerson メソッドが呼び出され、選択された行が更新されます。

<IgbInput @bind-Value="@_selectedPersonName"></IgbInput>
<IgbSelect @bind-Value="@_selectedPersonJobTitle">
    <IgbSelectItem Value="Developer">Developer</IgbSelectItem>
    <IgbSelectItem Value="Support">Support</IgbSelectItem>
    <IgbSelectItem Value="Manager">Manager</IgbSelectItem>
    <IgbSelectItem Value="Marketing">Marketing</IgbSelectItem>
    <IgbSelectItem Value="Sales">Sales</IgbSelectItem>
</IgbSelect>
<IgbButton @onclick="OnUpdatePerson">Upadate</IgbButton>

実行結果

この実装により、ユーザーは IgbGrid 上で行を選択し、フォームに表示された値を変更して「Update」ボタンを押すと、選択された行が更新されます。

関連ドキュメント

Tagged:

製品について

Ignite UI for Blazor