如何获取已检查的datagridview行

时间:2015-10-28 15:08:10

标签: vb.net

我写了代码
这使用户可以检查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

1 个答案:

答案 0 :(得分:0)

你必须知道复选框列的索引,然后你可以使用它:

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