BindingSource with DataTable in VB



序言:我已经很久没有使用WinForms了,也从未使用过VB,我正试图将DataGridView添加到用VB编写的应用程序中,该应用程序将显示来自DataTable的数据网格。

我在这里、这里和这里遵循了文档,在一个简单的测试示例中,我有代码

Public Class Form1
    Private count As Integer
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        count = count + 1
        Dim table As DataTable = BindingSource2.DataSource
        Dim row As DataRow
        row = table.NewRow()
        row("Col1") = "foo" + count.ToString()
        row("Col2") = "bar" + count.ToString()
        table.Rows.Add(row) 'throws System.InvalidOperationException here
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'BindingSource2.DataSource = New DataTable()
        'Dim table As DataTable = BindingSource2.DataSource
        Dim table As New DataTable
        Dim column1 As DataColumn = New DataColumn()
        column1.ColumnName = "Col1"
        column1.Caption = column1.ColumnName
        column1.DataType = System.Type.GetType("System.String")
        table.Columns.Add(column1)
        Dim column2 As DataColumn = New DataColumn()
        column2.ColumnName = "Col2"
        column2.Caption = column2.ColumnName
        column2.DataType = System.Type.GetType("System.String")
        table.Columns.Add(column2)
        'Dim keys(0) As DataColumn
        'keys(0) = column1
        'table.PrimaryKey = keys
        ' first row
        Dim row As DataRow = table.NewRow()
        row("Col1") = "beep"
        row("Col2") = "boop"
        table.Rows.Add(row)
        BindingSource2.DataSource = table
    End Sub
End Class

代码可以通过Form1_Load,但是在那里添加的条目没有显示在DataGridView中。然后,当调用Timer1_Tick时,它在上面指示的行处抛出一个System.InvalidOperationException异常。根据文档中给出的例子,我看不出我做错了什么。

问题:有人能帮忙吗?(a(为什么DataGridView没有反映Form1_Load末尾添加的数据?(b(为什么添加一行会导致异常?

p.s.我已经检查了调试,在table.Rows.Add(row)tablerow都包含正确的信息。

编辑:BindingSource是使用设计器添加并连接到DataGridView的,因此它的代码显示在From1.designer.vb中,我在这里没有显示。

解决方案(至少在我的情况下(是DataGridView.AutoGenerateColumns没有显示在设计面板中,默认情况下设置为False。我只是添加了行

DataGridView1.AutoGenerateColumns = True

到我的代码(在Form1_Load中(,它工作得很好。我在论坛上找到了解决方案,但现在找不到链接。如果我找到它,我会添加它。

我不知道该说什么。我准确地使用了你的代码,没有例外。它工作得很好。我想问题可能是Timer1。Interval可能太低了,这个值与你运行代码的机器的速度有关。如果你增加时间间隔怎么办?

至于没有显示的数据。。。将两列添加到DataGridView设置每个DataGridView列的DataPropertyName属性以与表的每个列的名称匹配(在"编辑列…"对话框中(。然后您将显示您的数据。

最新更新