2013-06-04 38 views
1

因此,我使用名爲MyMenuForm的表單中的此代碼。將Form1中的數據表從Form2中更改爲Visual Basic

Public Class MyMenuForm 

    Public Sub LoadForm(sender As Object, e As EventArgs) 
     DataGrid.DataSource = DataGridTable 
     DataGridTable.Columns.Add("Name", GetType(String)) 
     DataGridTable.Columns.Add("Verison", GetType(String)) 
     DataGridTable.Columns.Add("Compile", GetType(Button)) 
     DataGridTable.Columns.Add("Location", GetType(String)) 
     DataGridTable.Columns.Add("CompileLoc", GetType(String)) 
    End Sub 

    Public DataGridTable As DataTable 

End Class 

我希望能夠從一個叫AddForm不同的形式編輯DataGridTable

Public Class AddForm 

    Public Sub Add_Click(sender As Object, e As EventArgs) Handles AddButton.Click 
     MyMenuForm.DataGridTable.Rows.Add(NameBox(), VersionBox(), "Compile", LocationBox(), CompileBox()) 
    End Sub 

End Class 

當我點擊AddButton按鈕,我收到錯誤

Additional information: Object reference not set to an instance of an object. 

有誰知道爲什麼會這樣或者我該如何解決?我已經在我的能力範圍內搜索,並沒有找到解決辦法。請幫忙。

回答

0

嘗試在你的項目中創建新的模塊,然後聲明數據表你在那裏..

Public DataGridTable As DataTable 

不要在類的形式聲明公用..

所以,你可以在每個窗體類調用。 。

Public Class AddForm 

    Public Sub Add_Click(sender As Object, e As EventArgs) Handles AddButton.Click 
     DataGridTable.Rows.Add(NameBox(), VersionBox(), "Compile", LocationBox(), CompileBox()) 
    End Sub 

End Class 
0

LoadForm是否正確執行?看起來你沒有實例化一個新的DataTable。所以DataGridTable始終是Nothing。

0

您還沒有實例化DataGridTable,只要我可以看到,您只聲明瞭它。 您將需要一個

DataGridTable = New DataTable 

在某些時候,大概在LoadForm子

0

試試這個test project我在這個例子中

在這裏創建的解釋一點:

注意範圍是非常重要的。 Object reference not set to an instance of an object是一個非常常見的錯誤,通常表明需要某種架構調整。

以下是MyMenuForm類的設置。 DataTable被聲明爲該類的一個屬性,所以任何可以訪問該類的人都可以訪問該特定屬性。

Public Class MyMenuForm 

    Public DataGridTable As New DataTable 

    Private Sub LoadForm(sender As System.Object, e As System.EventArgs) Handles MyBase.Load 
     With DataGridTable.Columns 
      .Add("Name", GetType(String)) 
      .Add("Verison", GetType(String)) 
      .Add("Compile", GetType(Button)) 
      .Add("Location", GetType(String)) 
      .Add("CompileLoc", GetType(String)) 
     End With 
     DataGridView1.DataSource = DataGridTable 
    End Sub 

End Class 

您還需要確保你嘗試使用AddForm類添加行前MyMenuForm已創建。就我而言,我只是說作爲啓動窗體和點擊

Startup From

開闢了一個附加的形式在AddForm,請確保您引用DataGridTable財產上的MyMenuForm類,如下所示:

Private Sub AddButton_Click(sender As System.Object, e As System.EventArgs) Handles AddButton.Click 
    Dim row As DataRow = MyMenuForm.DataGridTable.NewRow() 

    With row 
     .Item("Name") = "TestName" 
     .Item("Verison") = "TestVerison" 
     .Item("Compile") = New Button 
     .Item("Location") = "TestLocation" 
     .Item("CompileLoc") = "TestCompileLoc" 
    End With 

    MyMenuForm.DataGridTable.Rows.Add(row) 

End Sub 
相關問題