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

VB.NET数据库项目:ListBox选中项联动填充TextBox问题求助

问题分析与修正方案

原代码存在的问题

  • 未定义变量dt:代码中With dt块引用的dt未声明,实际应操作已填充数据的dt1
  • 冗余列添加操作:da1.Fill(dt1)已从数据库获取Castmer表的所有列,无需手动重复添加列
  • 绑定逻辑错误:直接将TextBox绑定到dt1(DataTable)无法实现ListBox选中项与TextBox的自动同步,需通过BindingSource作为中间层
  • 选中项设置时机错误:ListBox1.SelectedValue = 0应在数据源绑定完成后设置,且需使用SelectedIndex而非SelectedValue

修正后的完整代码

1. 先在窗体类顶部声明BindingSource实例

Private BS As New BindingSource

2. 修正Form_Load事件代码

Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' 从数据库填充数据表
    Dim da1 As New OleDbDataAdapter("Select * from Castmer", Conn)
    Dim dt1 As New DataTable
    da1.Fill(dt1)

    ' 将DataTable绑定到BindingSource
    BS.DataSource = dt1

    ' 配置ListBox显示NEM列
    With ListBox1
        .DataSource = BS
        .DisplayMember = "NEM"
        .SelectedIndex = 0 ' 设置默认选中第一项
    End With

    ' 绑定DataGridView(如需保留)
    DataGridView1.DataSource = BS

    ' 将TextBox绑定到BindingSource,实现选中项自动同步
    TxtBook.DataBindings.Add("Text", BS, "NEM")
    TxtAuthor.DataBindings.Add("Text", BS, "DEN")
    TxtPublisher.DataBindings.Add("Text", BS, "PON")
    TxtPublish.DataBindings.Add("Text", BS, "ANON")
    txtPage.DataBindings.Add("Text", BS, "DATAC")
    TxtNote.DataBindings.Add("Text", BS, "TXTC")
End Sub

关键说明

  • 使用BindingSource作为DataTable与控件的中间层,ListBox选中项变化时,BindingSource会自动将当前行数据同步到绑定的TextBox,无需手动编写选中事件处理代码
  • 移除冗余的列添加代码,避免列重复定义引发的冲突
  • 统一所有控件绑定到同一个BindingSource,保证数据同步的一致性

内容的提问来源于stack exchange,提问作者خالد علي

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:27:32