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

从DataGridView双击事件传值至主窗体时遇类型转换错误

问题解决建议

1. 修复DoubleClick事件参数类型错误

DataGridView的DoubleClick事件传递的参数是MouseEventArgs,而非你代码里写的DataGridViewCellEventArgs,这就是类型转换错误的根源。推荐改用CellDoubleClick事件,该事件的参数天生就是DataGridViewCellEventArgs,更适配行/单元格双击的业务场景。

修改子窗体代码:

Private Sub CustomersDataGridView_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles CustomersDataGridView.CellDoubleClick
    Try
        ' 过滤表头行,只处理数据行
        If e.RowIndex < 0 Then Exit Sub
        
        Dim row As DataGridViewRow = CustomersDataGridView.Rows(e.RowIndex)
        Dim customerID As Integer = CInt(row.Cells(0).Value)

        Me.Tag = customerID
        Me.DialogResult = DialogResult.OK
    Catch ex As SqlException
        MessageBox.Show("SQL Server error # " & ex.Number & ": " & ex.Message, ex.GetType.ToString)
    Catch ex As InvalidCastException
        MessageBox.Show("无法将客户ID转换为数值类型", "数据错误")
    End Try
End Sub

2. 修复主窗体获取Tag的错误

你在主窗体里直接调用frmFindCustomerByState.Tag,这是访问类的静态成员,而非你创建的实例newStateForm的属性,会导致拿不到正确的选中值。需要改为访问实例的Tag:

修改主窗体代码:

Private Sub btnSearchByState_Click(sender As Object, e As EventArgs) Handles btnSearchByState.Click
    Try
        Dim newStateForm As New frmFindCustomerByState
        Dim selectedButton As DialogResult = newStateForm.ShowDialog()
        If selectedButton = Windows.Forms.DialogResult.OK Then
            txtFillByCustomerID.Text = newStateForm.Tag.ToString
        End If
    Catch ex As SqlException
        MessageBox.Show("SQL Server error # " & ex.Number & ": " & ex.Message, ex.GetType.ToString)
    Catch ex As NullReferenceException
        MessageBox.Show("未选择有效客户", "提示")
    End Try
End Sub

额外优化提示

  • 增加e.RowIndex >=0的判断,避免点击表头时触发无效逻辑
  • 补充类型转换、空引用等异常捕获,提升程序稳定性
  • 通过ShowDialog打开的子窗体,设置DialogResult.OK后会自动关闭,无需额外调用Close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:02:20