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

VB.NET中如何点击DataGridView单元格在另一窗体TextBox显示数据

解决DataGridView点击单元格打开窗体并加载数据的问题

你的代码核心问题是直接操作AddSupplier类的静态控件实例,但Formbackground方法里新建了一个独立的AddSupplier对象,之前的赋值根本没作用到这个新窗体上。下面是修正后的完整代码:

修正后的Formbackground方法

修改方法,让它接收一个已赋值好的AddSupplier实例:

Private Sub Formbackground(targetForm As Form)
    Dim formBackground As Form = New Form()

    Try
        formBackground.StartPosition = FormStartPosition.Manual
        formBackground.FormBorderStyle = FormBorderStyle.None
        formBackground.Opacity = 0.5R
        formBackground.BackColor = Color.Black
        formBackground.WindowState = FormWindowState.Maximized
        formBackground.TopMost = True
        formBackground.Location = Me.Location
        formBackground.ShowInTaskbar = False
        formBackground.Show()
        
        targetForm.Owner = formBackground
        targetForm.ShowDialog()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        formBackground.Dispose()
        targetForm.Dispose()
    End Try
End Sub

修正后的CellContentClick事件

先创建AddSupplier实例,给它的控件赋值,再传给Formbackground方法:

Dim key = 0

Private Sub suppliersDGV_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles suppliersDGV.CellContentClick
    ' 排除表头行点击
    If e.RowIndex < 0 Then Return
    
    Dim row As DataGridViewRow = suppliersDGV.Rows(e.RowIndex)
    
    ' 新建AddSupplier实例
    Using uu As New AddSupplier()
        ' 给当前实例的控件赋值,处理空值避免异常
        uu.txtSupplier.Text = row.Cells(0).Value?.ToString() ?? ""
        uu.txtPhone.Text = row.Cells(1).Value?.ToString() ?? ""
        uu.txtAddress.Text = row.Cells(3).Value?.ToString() ?? ""

        If String.IsNullOrEmpty(uu.txtAddress.Text) Then
            key = 0
        Else
            key = Convert.ToInt32(row.Cells(0).Value.ToString())
        End If
        
        ' 传递实例到背景窗体方法
        Formbackground(uu)
    End Using
End Sub

关键修改说明

  • 移除原代码中Formbackground内的AddSupplier实例创建逻辑,改为从外部传入已赋值的实例,确保操作的是即将打开的窗体对象
  • 用?.ToString() ?? ""处理单元格值为Null的情况,避免空引用异常
  • 增加表头行判断,防止点击表头触发事件时出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:05:13