忍耐我们,我是VB的新手。长话短说。我有一个VB应用程序,有几个按钮打开一个新的表单。我尝试使用Case选择将此表单重新用于多种用途。
2个按钮:
btnPing:
Private Sub btnPing_Click(sender As Object, e As EventArgs) Handles btnPing.Click
dataTransferBtnCase = "ping"
formDataTransfer.ShowDialog()
btnRobocopy.Enabled = True
End Sub
和btnRobocopy
Private Sub btnRobocopy_Click(sender As Object, e As EventArgs) Handles btnRobocopy.Click
dataTransferBtnCase = "robocopy"
formDataTransfer.Show()
End Sub
在每个按钮中,它将值赋给变量dataTransferBtnCase。
现在,在该表单上,我有以下代码:
Public Class formDataTransfer
'Clear the variable right off the bat
Public dataTransferBtnCase As String = ""
Private Sub formDataTransfer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oldPath As String = viewInstall.txtOldHostname.Text
Dim newPath As String = viewInstall.txtNewHostname.Text
dataTransferBtnCase = viewInstall.dataTransferBtnCase
Select Case dataTransferBtnCase
Case "ping"
Me.Text = "Pinging " & oldPath
ExecuteCommand("cmd.exe", "/D /c ping " & oldPath)
Case "robocopy"
Me.Text = "Robocopy from " & viewInstall.txtOldHostname.Text & " to " & viewInstall.txtNewHostname.Text
ExecuteCommand("robocopy.exe", "C:\temp\robo1 C:\temp\robo2 /E /XF file *.dat *.dat.log *.dat.log1 /log:robolog.log")
Case Else
Me.Text = "lol idk!"
MessageBox.Show("An unknown error has occurred!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Select
dataTransferBtnCase = ""
viewInstall.dataTransferBtnCase = ""
End Sub
End Class
每次btnPing_Click子工作都应该如此。但是,btnRobocopy_Click子只有在您单击一次,关闭新窗体窗口,然后再次单击该按钮后才能工作。我确定这是因为我没有在某处正确清除变量,我只是不知道在哪里。有什么帮助吗?
答案 0 :(得分:2)
问题在于您使用对话框的方式:
Private Sub btnPing_Click(sender As Object,
e As EventArgs) Handles btnPing.Click
dataTransferBtnCase = "ping"
formDataTransfer.ShowDialog()
btnRobocopy.Enabled = True
End Sub
如果你使用ShowDialog
,之后你也应该Dispose
。按原样,您将重新显示旧实例,并且所有旧数据仍然存在。
在这方面,对话与常规Form
不同。当我们完成一个表单并关闭它时,NET为我们处理了一些事情。对话框不通常已关闭(通常只是隐藏),因此我们可以从中获取信息。
这将创建一个新的表单实例,显示它然后在完成后处理它:
Dim dlgR As DialogResult
Using dlg As New formDataTransfer
' use a public property maybe to pass the data
dlg.ActionToTake = "ping"
dlgR = dlg.ShowDialog()
' ... do stuff
End Using ' dispose of the dialog
由于表单没有自动处理 - 你可能只有Hide
代码 - 你正在重用最后一个实例。