-在我使用hide()和show()在表单之间切换之后,我创建了2种表单。
-在第二种形式中,我创建数据表(绑定到数据网格)和主键以供数据表使用find()。
-按第二个表格的[BACK]按钮返回第一个表格(使用hide()和show()函数),然后再次使用第二个表格应用程序。运行时错误显示此[System.Data.Missing.PrimaryKeyException:表没有主键]
第一表格
Public Class MainMenu
Public MainForm As MainMenu
Public AssetCheckForm As AssetCheck
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
AssetCheckForm.Show()
MainForm.Hide()
End Sub
Public Sub MainMenu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MainForm = New MainMenu()
AssetCheckForm = New AssetCheck()
End Sub End Class
第二张表格
Dim dtAsset As New DataTable("AssetTable")
Public Sub readData()
If readStatus = 0 Then
Try
Dim splits As String()
Using sr As StreamReader = New StreamReader(inputcsvname)
'read the first line for the table columns
splits = sr.ReadLine.Split(","c)
For i As Integer = 0 To UBound(splits)
dtAsset.Columns.Add(splits(i))
Next
'read the rest of the lines to add rows
Do While Not sr.EndOfStream
splits = sr.ReadLine.Split(","c)
dtAsset.Rows.Add(splits)
Loop
End Using
Catch ex As Exception
Finally
End Try
dtAsset_display = dtAsset.Copy()
totalcount.Text = getRowsCount(dtAsset_display)
dtAsset.Columns("AsstCode").Unique = True
dtAsset.PrimaryKey = New DataColumn() {dtAsset.Columns("AsstCode")}
'bind display part to DataGrid
DataGrid1.DataSource = dtAsset
Private Sub BackButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonF4.Click
clearData()
MainMenu.MainForm.Show()
MainMenu.AssetCheckForm.Hide()
End Sub
我想我错过了有关VB.net WinForm概念的信息。 有人知道这个错误是什么意思吗?
答案 0 :(得分:0)
您正在MainForm = New MainMenu()
中呼叫MainForm
的事实,这意味着您现在拥有MainForm
的两个实例。
因此,当您致电MainMenu.MainForm.Show()
时,您将显示新实例,而不是现有实例。
您需要对此进行更改,以便将对现有MainForm
的引用存储在AssetCheckForm
表单中。
类似这样的东西:
Public Class MainMenu
Private AssetCheckForm As AssetCheckForm
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.AssetCheckForm = New AssetCheckForm
Me.AssetCheckForm.MainMenu = Me
Me.Hide()
Me.AssetCheckForm.Show()
End Sub
End Class
Public Class AssetCheckForm
Friend MainMenu As MainMenu
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.MainMenu.Show()
Me.Close()
End Sub
End Class