跟我们一起,我是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子只有在您单击一次,关闭新窗体窗口并再次单击该按钮后才能工作.我确定这是因为我没有在某处正确清除变量,我只是不知道在哪里.有帮助吗?
解决方法
问题是您使用对话框的方式:
Private Sub btnPing_Click(sender As Object,e As EventArgs) Handles btnPing.Click dataTransferBtnCase = "ping" formDataTransfer.ShowDialog() btnRobocopy.Enabled = True End Sub
如果你使用ShowDialog,你也应该在之后处理它.按原样,您将重新显示旧实例,所有旧数据仍然存在.
在这方面,对话与常规表格不同.当我们完成一个表单并关闭它时,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