You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中点击编辑列后设置DataGridView指定行某列可编辑

解决方案

问题出在你直接设置了整列的ReadOnly属性,这会影响所有行。要实现仅选中行的Qty列可编辑,需要通过CellBeginEdit事件逐单元格控制编辑权限,配合状态变量记录编辑状态。

步骤1:定义状态变量

在窗体类中添加布尔变量,标记是否开启Qty列的编辑模式:

Private IsEditingQty As Boolean = False

步骤2:保留Form1_Load原有设置

初始化时保持Qty列默认只读:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView2.DataSource = itrservice.GetLoadStocksoutdetailMaster()
    DataGridView2.Columns("No").ReadOnly = True
    DataGridView2.Columns("Invnop").ReadOnly = True
    DataGridView2.Columns("CodeProduct").ReadOnly = True
    DataGridView2.Columns("Qty").ReadOnly = True ' 默认整列只读
End Sub

步骤3:修改DataGridView1的点击事件

点击编辑列时开启编辑模式,并自动激活选中行的Qty列编辑:

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    If e.ColumnIndex = 4 Then
        If DataGridView2.SelectedRows.Count = 0 Then
            Return
        End If
        IsEditingQty = True
        ' 直接进入选中行的Qty列编辑状态
        Dim targetRow = DataGridView2.SelectedRows(0)
        DataGridView2.BeginEdit(True)
        DataGridView2.CurrentCell = targetRow.Cells("Qty")
    End If
End Sub

步骤4:添加DataGridView2的CellBeginEdit事件

拦截编辑请求,仅允许符合条件的单元格编辑:

Private Sub DataGridView2_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView2.CellBeginEdit
    ' 仅当当前单元格是Qty列、处于编辑模式、且是选中行时,允许编辑
    If e.ColumnIndex = DataGridView2.Columns("Qty").Index Then
        e.Cancel = Not (IsEditingQty AndAlso DataGridView2.Rows(e.RowIndex).Selected)
    End If
End Sub

步骤5:添加DataGridView2的SelectionChanged事件

切换选中行时关闭编辑模式,恢复只读:

Private Sub DataGridView2_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView2.SelectionChanged
    IsEditingQty = False
End Sub

原理说明

  • IsEditingQty变量控制是否处于编辑触发状态
  • CellBeginEdit事件拦截编辑请求,仅允许选中行的Qty列进入编辑
  • 切换选中行时自动关闭编辑模式,确保其他行的Qty列保持只读

内容的提问来源于stack exchange,提问作者roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:11:09