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

Visual Basic实现DataGridView选中行数据在TextBox显示问题

解决DataGridView选中行同时显示firstname和surname到文本框的问题

嘿,我来帮你搞定这个问题!你现在的情况应该是只获取了单个单元格的数据,没同时提取选中行里的firstname和surname两个字段。咱们换个思路,直接针对选中的整行来操作,不用遍历单元格,这样更简单高效。

给你调整后的代码,直接用SelectedRows来获取整行数据:

Private Sub btnSelect_Click(sender As Object, e As EventArgs) Handles btnSelect.Click
    ' 先检查有没有选中行,避免空报错
    If staffList.SelectedRows.Count > 0 Then
        ' 取选中的第一行(如果是单选模式,这个就够用了)
        Dim selectedRow As DataGridViewRow = staffList.SelectedRows(0)
        
        ' 提取两个字段的值,注意这里的列名要和你的DataGridView列名完全一致
        Dim firstName As String = selectedRow.Cells("firstname").Value.ToString()
        Dim surName As String = selectedRow.Cells("surname").Value.ToString()
        
        ' 把名和姓拼接起来显示到文本框
        txtname.Text = $"{firstName} {surName}"
    Else
        ' 没选中行的时候给个提示
        MessageBox.Show("请先选择一行员工数据哦!")
    End If
End Sub

另外还要注意两个小细节:

  • 如果你不确定列名是否正确,也可以用列的索引(比如Cells(0)对应第一列),但用列名更直观,后续改列顺序也不容易出错
  • 如果数据库里这两个字段可能为空,记得加个空值判断,避免程序报错:
    Dim firstName As String = If(IsDBNull(selectedRow.Cells("firstname").Value), "", selectedRow.Cells("firstname").Value.ToString())
    Dim surName As String = If(IsDBNull(selectedRow.Cells("surname").Value), "", selectedRow.Cells("surname").Value.ToString())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:39:03