2011-09-05 35 views
0

序言: 同時,也從未在VB我想一個DataGridView添加到VB編寫的應用程序,它會從顯示數據的網格具有不與WinForms的工作了很DataTable的BindingSource在VB中的DataTable

我跟着文檔hereherehere和在一個簡單的測試例子我的代碼

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異常。基於文檔中給出的示例,我看不出我做錯了什麼。

問:任何人可以幫助請與(一)爲何不DataGridViewForm1_Load年底反映添加的數據(B)爲什麼添加行引起異常?

P.s.我檢查了調試,並在table.Rows.Add(row)table包含正確的信息,如row

編輯: BindingSource被添加並使用設計器連接到DataGridView,所以它的代碼顯示在From1.Designer.vb中,我沒有在這裏顯示。

+0

你應該用'GetType(String)'替換System.Type.GetType(「System.String」)'。它更簡潔,並使用強大的打字。 –

+0

好吧,我已經改變了它,但它沒有解決任何問題。 – Dan

回答

1

(在這裏我的情況下至少)的解決方案是,該DataGridView.AutoGenerateColumns未在設計面板顯示和是默認設置爲False。我只是添加了行

DataGridView1.AutoGenerateColumns = True 

我的代碼(在Form1_Load),它的工作完美。我在論壇上找到了解決方案,但現在找不到鏈接。如果我找到它,我會添加它。

0

我不知道該說什麼。我完全使用你的代碼,並沒有發生異常。它工作得很好。我猜可能是這個問題,也許是Timer1.Interval的值可能太低,以至於運行代碼的機器速度有多快。如果你增加間隔時間會怎樣?

至於不被顯示的數據......添加兩列到DataGridView設置每個DataGridView的列的DataPropertyName物業,以配合每個表的列名(在編輯Colums ...對話框)的。然後你會得到你的數據顯示。