0

I have a sub that opens a file dialog when the user clicks a button, then uses the file name to extract it (my program extracts zip files). If the user does not pick a .zip file a message pops up telling to select the correct format. This worked fine except if they canceled the open file dialog the message would still pop up so is there a way to exit the sub if the user cancels? Here is some code:

Private Sub AddJarMod_Click(sender As Object, e As EventArgs) Handles AddJarMod.Click
    addModDialog.ShowDialog()
    newJarModDir = addModDialog.FileName
    newJarMod = System.IO.Path.GetFileNameWithoutExtension(newJarModDir)
    If System.IO.Path.GetExtension(newJarModDir) = ".zip" Then
        jarModList.Items.Add(newJarMod)
        devConsoleList.Items.Add(newJarModDir)
    ElseIf System.IO.Path.GetExtension(newJarModDir) <> ".zip" Then
        MsgBox("File extension not a zip")
    End If
End Sub

I'm relatively new to coding and the forums so sorry if my code or the post isn't completely correct.

4

2 回答 2

1

您只需要检查DialogResult从模态表单返回的内容。这样,您的代码仅在ok从表单中获取时才会执行。

Private Sub AddJarMod_Click(sender As Object, e As EventArgs) Handles AddJarMod.Click
 If addModDialog.ShowDialog() = DialogResult.Ok Then
  newJarModDir = addModDialog.FileName
  newJarMod = System.IO.Path.GetFileNameWithoutExtension(newJarModDir)
  If System.IO.Path.GetExtension(newJarModDir) = ".zip" Then
    jarModList.Items.Add(newJarMod)
    devConsoleList.Items.Add(newJarModDir)
  ElseIf System.IO.Path.GetExtension(newJarModDir) <> ".zip" Then
    MsgBox("File extension not a zip")
  End If
 End If
End Sub
于 2013-07-25T00:16:54.080 回答
0

更好的方法可能是将 OpenFileDialog 限制为仅显示 zip 文件。

addModDialog.Filter = "zip file (*.zip)|*.zip;"
If addModDialog.ShowDialog() = DialogResult.Ok Then
...
于 2013-07-25T07:01:08.157 回答