进度条,等待表格

时间:2015-08-13 17:14:32

标签: .net vb.net

在我的主窗体中,我有一个按钮可以跨多个数据库加载很多存储过程。我想在加载时创建进度/等待表单。当我按下按钮时,我将它显示在waitdialog上 我有一个调用workerDoWork的后台工作程序。 在该方法中,我想调用包含所有代码的主窗体来进行加载。当我把它公开时,我可以打电话给它。但主要形式内有如此多的引用,全局变量,不同的方法被称为它不起作用。如何在不必将所有代码移动到等待表单的情况下使其工作。

等待表单中的代码。

Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
    MyBase.OnLoad(e)

    _worker = New BackgroundWorker()
    AddHandler _worker.DoWork, AddressOf WorkerDoWork
    AddHandler _worker.RunWorkerCompleted, AddressOf WorkerCompleted

    _worker.RunWorkerAsync()
End Sub

' This is executed on a worker thread and will not make the dialog unresponsive.  If you want
' to interact with the dialog (like changing a progress bar or label), you need to use the
' worker's ReportProgress() method (see documentation for details)
Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    'Dim main As New frmMain()
    frmMain.LoadARData()
    ' MsgBox("hi there ")

End Sub




' This is executed on the UI thread after the work is complete.  It's a good place to either
' close the dialog or indicate that the initialization is complete.  It's safe to work with
' controls from this event.
Private Sub WorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
    Me.DialogResult = Windows.Forms.DialogResult.OK
    Me.Close()
End Sub

1 个答案:

答案 0 :(得分:0)

你有:

frmMain.LoadARData()

使用frmMain的默认实例,很可能与您在屏幕上显示的那个不一致(导致错误和意外行为)。

您需要引用正确的frmMain实例才能使其正常工作。解决此问题的一种方法是将对frmMain的引用传递给Show()/ ShowDialog()调用:

' ... running from within frmMain ...
Dim progress As New frmProgress()
progress.ShowDialog(Me) ' <-- passing in "Me" (the reference to frmMain)

现在,在进度表单中,您可以将Owner属性转换为frmMain类型并调用所需的方法:

Private Sub WorkerDoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Dim main As frmMain = DirectCast(Me.Owner, frmMain)
    main.LoadARData()
End Sub