【问题标题】:Populate DataSet into a ComboBox and fill a TextBox将 DataSet 填充到 ComboBox 并填充 TextBox
【发布时间】:2019-07-23 19:12:48
【问题描述】:

我正在尝试从 DataSet 填充 ComboBox,而 DataSet 的一列也应该填充 TextBox。

示例表:

sid |  sname | surl
---------------------------
  1 | Google | www.google.com
  2 | Bing   | www.bing.com
  3 | Yahoo  | www.yahoo.com

现在我想要GoogleBing 等作为组合框中的SelectedText,而SelectedValue12 等。
当我选择Google 时,我希望将www.google.com 填充到TextBox 中。

代码:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim tb As DataTable = Dataset1.Table1

        ComboBox1.DataSource = tb
        ComboBox1.DisplayMember = "sname"
        ComboBox1.ValueMember = "sid"

        TextBox1.Text = DataSet1.Table1.FindBysid(ComboBox1.SelectedValue).surl
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        TextBox1.Text = DataSet1.Table1.FindBysid(ComboBox1.SelectedValue).surl
    End Sub
End Class

Afaik,初始选择正常工作。
ComboBox 选择 Google 并将 TextBox1.Text 设置为 www.google.com
但随后出现以下错误:

System.InvalidCastException:“类型 DataRowView 的无效转换 输入整数。

这发生在SelectedIndexChanged 事件上。
我真的不知道为什么第一个 TextBox 分配工作得很好,而事件中的第二个在转换错误时运行。

有什么建议吗?

【问题讨论】:

    标签: .net vb.net winforms data-binding dataset


    【解决方案1】:

    用于测试BindingSourceBinding 类功能的示例代码。

    构建一个包含一些字段的 DataTable(如问题中提供的那样);使用 DataTable 作为 BindingSource 对象的 DataSource。

    然后将 BindingSource 设置为 ComboBox 的 DataSource(此处为 ComboBox1)。
    DisplayMemberValueMember 也设置为所需的列(可能在分配控件的数据源之前设置这些属性)。
    然后使用相同的 DataSource(之前定义的 BindingSource 对象)将 Binding 添加到 TextBox Text 属性。

    当 ComboBox SelectedItem 更改(在代码中或由于用户选择)时,TextBox.Text 属性将相应更新:

    Friend dtSource As BindingSource = Nothing
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim dt As New DataTable("TestTable")
        dt.Columns.AddRange({
            New DataColumn("sid", GetType(Integer)) With {
              .AutoIncrement = True, .AutoIncrementStep = 1, .AutoIncrementSeed = 1
            },
            New DataColumn("sname", GetType(String)),
            New DataColumn("surl", GetType(String))
        })
    
        dt.Rows.Add({Nothing, "Google", "www.google.com"})
        dt.Rows.Add({Nothing, "Bing", "www.bing.com"})
        dt.Rows.Add({Nothing, "Yahoo", "www.yahoo.com"})
    
        dtSource = New BindingSource(dt, "")
    
        ComboBox1.ValueMember = "sid"
        ComboBox1.DisplayMember = "sname"
        ComboBox1.DataSource = dtSource
    
        TextBox1.DataBindings.Add(
            New Binding("Text", dtSource, "surl", False, DataSourceUpdateMode.OnPropertyChanged))
        ComboBox1.SelectedIndex = 0
    End Sub
    

    【讨论】:

    • 像魅力一样工作。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2013-12-19
    • 1970-01-01
    • 2014-03-06
    相关资源
    最近更新 更多