System.StackOverflowException未处理 - 尝试调用表单,我收到此错误

时间:2014-11-07 01:13:02

标签: vb.net forms exception recursion

我运行此代码时出现上述错误。当我尝试运行具有3种形式的VBNet程序时。

我只是想将列表项从一个表单传递到另一个表单,但是在程序编译之前我收到错误。

Public Class frmCart


Dim frmComic As New comicBooks
Dim frmAudio As New audioBooks

Public decSubTotal As Decimal



Private Sub ShowToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowToolStripMenuItem.Click

    frmComic.ShowDialog()

End Sub


Private Sub ShowDialogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowDialogToolStripMenuItem.Click
    frmAudio.ShowDialog()
End Sub

结束班

现在frmComic是

Public Class comicBooks

Dim frmCartForm As New frmCart

Public decPrice1 As Decimal = 20.95D
Public decPrice2 As Decimal = 10.50D


Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

    Select Case lstComicBooks.SelectedItem

        Case "Comic #1 (Print)"
            frmCart.lstProductsSelected.Items.Add("Comic #1")
            frmCart.decSubTotal += decPrice1
        Case "The History of Scotland (Print)"
            frmCart.lstProductsSelected.Items.Add("Comic #2")
            frmCart.decSubTotal += decPrice2
        Case Else
            MessageBox.Show("Please select a Comic")
    End Select

End Sub

结束班

如果我只拨打一次Dialog,我就不知道它为什么会递归。

由于

2 个答案:

答案 0 :(得分:0)

  1. 类漫画书实例化一个新的frmCart。
  2. frmCart实例化一个新的漫画书
  3. 回到1
  4. 删除漫画书中的frmCartForm声明

答案 1 :(得分:0)

为了避免递归,您应该将当前的frmCart实例传递给构造函数中的comicBooks类。像这样:

Public Class frmCart
    Dim frmComic As New comicBooks(Me)   '<--- Pass current form into constructor
End Class

Public Class comicBooks

    Dim frmCartForm As frmCart  '<--- variable to hold passed in form instance

    Public Sub New(cartForm As frmCart)    '<--- Constructor to take instance of form
        Me.frmCartForm = cartForm          '<--- Assign passed in reference to our variable
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        'Use frmCartForm here
    End Sub
End Class