簡體   English   中英

如何獲取datagridview的選中行

[英]How to get the checked rows of datagridview

我已經寫了代碼
這使用戶能夠檢查 datagridview 中的復選框列,當用戶單擊確定按鈕時,所選行將顯示在 msgbox 中。
我想將它們發送到另一個表單(在列表框中),而不是在 msgbox 中顯示行。

Public Class Form

WithEvents bsCustomer As New BindingSource 

Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim dt As New DataTable
    dt.Columns.Add(New DataColumn With {.ColumnName = "Check", .DataType = GetType(Boolean)})

    Dim con As New SqlConnection(ConString)
    Dim Command = New SqlCommand()
    Command.Connection=con
    Command.CommandText="SELECT ID, Name FROM Table1"
    con.Open()
    dt.Load(command.ExecuteReader)

    For Each row As DataRow In dt.Rows
        row.SetField(Of Boolean)("Check", False)
    Next

    dt.AcceptChanges()
    bsCustomer.DataSource = dt
    Datagridview1.DataSource = bsCustomer 

End Sub  

Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
    Dim Names =
        (
            From T In Datagridview1.GetChecked("Check")
            Select CStr(T.Cells("name").Value)
        ).ToArray

    If Names.Count > 0 Then
        MessageBox.Show(String.Join(Environment.NewLine, Names))    
    Else
        MessageBox.Show("Nothing checked")
    End If

End Sub 

Public Function GetChecked(ByVal GridView As DataGridView, ByVal ColumnName As String) As List(Of DataGridViewRow)
    Return (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() Where CBool(Rows.Cells(ColumnName).Value) = True).ToList
End Function

您必須知道復選框列的索引,然后才能使用:

IEnumerable<DataGridViewRow> GetCheckedRows(DataGridView grid, int checkboxColumnIndex)
{
    List<DataGridViewRow> checkedRows = new List<DataGridViewRow>();
    for (int rowIndex = 0; rowIndex < grid.RowCount; rowIndex++)
    {
        var chkCell = grid[checkboxColumnIndex, rowIndex] as DataGridViewCheckBoxCell;
        bool isChecked = (bool)chkCell.EditedFormattedValue;
        if (isChecked)
            checkedRows.Add(grid.Rows[rowIndex]);
    }
    return checkedRows;
}

現在您必須有一個Form2實例才能將這些行傳遞給它,例如通過公共屬性或方法。 與其傳遞DataGridViewRow ,不如傳遞選定的對象。 但是由於您沒有提到數據源,因此我使用了行。


VB.NET:

Function GetCheckedRows(grid As DataGridView, checkboxColumnIndex As Integer) As IEnumerable(Of DataGridViewRow)
    Dim checkedRows As New List(Of DataGridViewRow)
    For rowIndex As Integer = 0 To grid.RowCount - 1
        Dim chkCell = TryCast(grid(checkboxColumnIndex, rowIndex), DataGridViewCheckBoxCell)
        Dim isChecked As Boolean = CBool(chkCell.EditedFormattedValue)
        If isChecked Then
            checkedRows.Add(grid.Rows(rowIndex))
        End If
    Next
    Return checkedRows
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM