2013-06-04 34 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 
相关问题