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

Winforms/VB.NET:如何获取DataGridView的ID列值作为窗体参数

解决DataGridView选中行ID值传递问题

要获取DataGridView中选中行的prdCod列值并传递给frmDetailProd,核心是先确认存在选中行,再读取对应列的数值,具体实现如下:

核心修改点

  1. 先判断DataGridView是否有选中行,避免空引用异常
  2. 读取选中行的prdCod列值,注意处理空值情况

修改后的完整代码

Public Class frmConsProd

    Private Sub tsbCons_Click(sender As Object, e As EventArgs) Handles tsbConsult.Click
            Try
                ' 检查是否选中了行
                If DataGridView1.SelectedRows.Count > 0 Then
                    Dim selectedRow = DataGridView1.SelectedRows(0)
                    ' 处理列值为空的情况
                    If Not IsDBNull(selectedRow.Cells("prdCod").Value) Then
                        Dim prdCodValue As String = selectedRow.Cells("prdCod").Value.ToString()
                        
                        Using frm As New frmDetailProd("Consult", prdCodValue)
                            frm.txtPrdCod.Enabled = True
                            frm.txtPrdCod.Text = prdCodValue
                            frm.ShowDialog()
                        End Using

                        tsbRefresh.PerformClick()
                    Else
                        MsgBox("选中的产品ID为空", MsgBoxStyle.Warning)
                    End If
                Else
                    MsgBox("请先选择一条产品记录", MsgBoxStyle.Information)
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
            End Try
    End Sub
End Class

注意事项

  • 将代码中的DataGridView1替换为你实际使用的DataGridView控件名称
  • 如果prdCod是数值类型(如Integer),可根据需求调整类型转换逻辑,比如直接转为Integer而非String

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:40:46