如何勾选DataGridView多行复选框并将值存入变量?
解决方案
1. 修复多行复选框勾选问题
首先确保DataGridView的基础配置正确:
- 在设计器中将
DGV_SEARCH的MultiSelect属性设为True,开启多行选择权限 - 添加
DataGridViewCheckBoxColumn作为勾选列(命名为DGV_SELECTED),用布尔值直接管理选中状态,无需手动模拟0/1数值
2. 实现复选框勾选事件
使用CellContentClick事件更精准(仅点击复选框区域时触发),代码如下:
Private Sub DGV_SEARCH_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV_SEARCH.CellContentClick ' 只处理复选框列的点击,排除无效行 If e.ColumnIndex = DGV_SEARCH.Columns("DGV_SELECTED").Index AndAlso e.RowIndex >= 0 Then Dim currentRow = DGV_SEARCH.Rows(e.RowIndex) ' 切换复选框状态(默认点击会自动切换,若有自定义逻辑可在此扩展) currentRow.Cells("DGV_SELECTED").Value = Not CBool(currentRow.Cells("DGV_SELECTED").Value) End If End Sub
3. Oracle数据查询与DataGridView绑定
添加数据加载逻辑,将Oracle查询结果绑定到控件:
Imports Oracle.ManagedDataAccess.Client ' 根据你的Oracle驱动版本选择 Imports System.Data Private Sub LoadEmployeeData() Dim connStr As String = "Data Source=你的Oracle数据源;User Id=用户名;Password=密码;" Using conn As New OracleConnection(connStr) Dim sql As String = "SELECT employeeNo, employeeName FROM Employee" Using cmd As New OracleCommand(sql, conn) conn.Open() Dim adapter As New OracleDataAdapter(cmd) Dim dt As New DataTable() adapter.Fill(dt) ' 绑定数据并插入复选框列 DGV_SEARCH.DataSource = dt Dim checkColumn As New DataGridViewCheckBoxColumn() checkColumn.Name = "DGV_SELECTED" checkColumn.HeaderText = "选择" DGV_SEARCH.Columns.Insert(0, checkColumn) End Using End Using End Sub
4. 收集选中行数据到List
建议用实体类存储更清晰,也可直接用List(Of String):
方式1:用实体类存储(推荐)
' 定义Employee实体类 Public Class Employee Public Property EmployeeNo As String Public Property EmployeeName As String End Class ' 获取选中项方法 Private Function GetSelectedEmployees() As List(Of Employee) Dim selectedList As New List(Of Employee) For Each row As DataGridViewRow In DGV_SEARCH.Rows ' 跳过自动生成的新行 If row.IsNewRow Then Continue For ' 判断复选框是否选中 If CBool(row.Cells("DGV_SELECTED").Value) Then Dim emp As New Employee() emp.EmployeeNo = row.Cells("employeeNo").Value.ToString() emp.EmployeeName = row.Cells("employeeName").Value.ToString() selectedList.Add(emp) End If Next Return selectedList End Sub ' 调用示例(比如按钮点击事件) Private Sub btnGetSelected_Click(sender As Object, e As EventArgs) Handles btnGetSelected.Click Dim selectedEmployees = GetSelectedEmployees() ' 后续可遍历selectedEmployees做业务处理 End Sub
方式2:用List(Of String)存储
Private Function GetSelectedEmployeeStrings() As List(Of String) Dim selectedList As New List(Of String) For Each row As DataGridViewRow In DGV_SEARCH.Rows If row.IsNewRow Then Continue For If CBool(row.Cells("DGV_SELECTED").Value) Then selectedList.Add(row.Cells("employeeNo").Value.ToString()) selectedList.Add(row.Cells("employeeName").Value.ToString()) End If Next Return selectedList End Function
内容的提问来源于stack exchange,提问作者FMH94
相关产品推荐
相关产品推荐

