序言: 同時,也從未在VB我想一個DataGridView
添加到VB編寫的應用程序,它會從顯示數據的網格具有不與WinForms的工作了很DataTable
。的BindingSource在VB中的DataTable
我跟着文檔here,here和here和在一個簡單的測試例子我的代碼
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
異常。基於文檔中給出的示例,我看不出我做錯了什麼。
問:任何人可以幫助請與(一)爲何不DataGridView
在Form1_Load
年底反映添加的數據(B)爲什麼添加行引起異常?
P.s.我檢查了調試,並在table.Rows.Add(row)
table
包含正確的信息,如row
。
編輯: BindingSource被添加並使用設計器連接到DataGridView,所以它的代碼顯示在From1.Designer.vb中,我沒有在這裏顯示。
你應該用'GetType(String)'替換System.Type.GetType(「System.String」)'。它更簡潔,並使用強大的打字。 –
好吧,我已經改變了它,但它沒有解決任何問題。 – Dan