0

VB.NET WinForms アプリケーションでは、最初の列にバインドされていない列としてチェックボックスを持つ DataGridView があります。チェックボックスがオンになっている各行を行のコレクションに追加する必要があります。

以下のコードを使用して行を反復処理し、チェックボックスがオンになっている行を見つけます。

For Each row As DataGridViewRow In dgvEmployees.Rows

    Dim chkCell As DataGridViewCheckBoxCell = DirectCast(row.Cells(0), DataGridViewCheckBoxCell)
    If Convert.ToBoolean(chkCell.Value) = True Then
        Console.WriteLine("This should be the Emp No of the checked row: " & row.Cells(1).Value.ToString())
    End If

Next

ただし、チェックボックスがオンになっている最後の行がありません。つまり、3 つのチェックボックスをオンにすると、コンソール出力に最初の 2 つのチェックされた行の「Emp No」が表示されます。

インデックス作成がゼロの問題のように動作していると考えて、カウンターを使用した反復も試しました。

For rowNum As Integer = 0 To dgvEmployees.Rows.Count - 1
    Dim currentRow As DataGridViewRow = dgvEmployees.Rows(rowNum)
    Dim chkCell As DataGridViewCheckBoxCell = DirectCast(currentRow.Cells(0), DataGridViewCheckBoxCell)

    If Convert.ToBoolean(chkCell.Value) = True Then
        Console.WriteLine("This should be the emp no of the checked row: " & currentRow.Cells(1).Value.ToString())
    End If

Next

しかし、私はそのコードで同じ動作をします。Integer = 0 や Rows.Count - 1 などを変更してみましたが、どちらも役に立ちませんでした。

重要な場合は、DataGridView の SelectionMode を CellSelect に設定する必要があります。

アップデート

テーブルには、datagridview が入力されている694のレコードがあります。

コンソール出力を追加して、rows.count 値を取得しました。

Console.WriteLine("Num rows: " & dgvEmployees.Rows.Count)

データグリッドビューの最後の行が新しい行のエントリを許可するためにそこにあるため、これは理にかなっています(しかし、2 番目の反復メソッドの Count - 1 がそれ​​を説明すると考えていたでしょう。)

私も追加しました

Console.WriteLine("Row index: " & chkcell.RowIndex)

チェックされたチェックボックスの If チェックの直前で、1 行目、3 行目、5 行目がチェックされている (インデックス 0、2、4) と、出力されたものは次のとおりです。

Num rows: 695
Row index: 0
this should be the emp no of the checked row: ACS175
Row index: 1
Row index: 2
this should be the emp no of the checked row: AJAW03
Row index: 3
Row index: 4
Row index: 5
Row index: 6

Row index: 4 行の後に「this should be...」という出力があったはずです。

4

1 に答える 1

1

チェックした後、フォーカスを別のセルに移動していないため、チェックした最後のチェックボックスは DataGridView によってコミットされていないようです。反復コードを実行する前に、これを試してください。

If dgvEmployees.IsCurrentCellDirty Then
    dgvEmployees.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If 
于 2014-11-20T19:14:35.733 に答える