gpt4 book ai didi

vb.net - 在 openFileDialog 上按下 Cancel 按钮时,如何才能没有错误?

转载 作者:行者123 更新时间:2023-12-01 15:25:02 25 4
gpt4 key购买 nike

在提问之前,我在互联网上做了很多搜索,但没有找到我的问题的答案。我有一个带有按钮的表单和两个类。当我按下表单上的按钮时,将打开一个对话框以从磁盘中选择一个 file.txt。如果我按下打开按钮,程序将继续正确执行代码中所写的操作。如果我按下取消按钮,程序会引发异常:

System.NullReferenceException: ‘Reference to an object not set on an object instance.' Path was Nothing. (On Class FilePan nomeFilePan = path.Replace("1319", "panasonic") + _nomeFile + ".pan")

我怎样才能将程序发送回表单,在那里我可以再次按下按钮打开文件或关闭程序?

Imports System
Public Class Form1
Dim _fileTxt As FileTxt = New FileTxt()
Dim CreaPan As FilePan = New FilePan()

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_fileTxt.SetFileTxt()
CreaPan.SetFilePan(_fileTxt.GetNomeFile(), _fileTxt.GetPath())
End Sub
End Class


Public Class FileTxt
Dim path As String
Dim nomeFile As String
Dim nomeFileTxt As String

Public Sub SetFileTxt()
Dim openFileDialog1 As New OpenFileDialog() With
{
.InitialDirectory = "",
.Filter = "Txt file|*txt",
.FilterIndex = 1,
.RestoreDirectory = True,
.Title = "Seleziona file"
}
If openFileDialog1.ShowDialog() = DialogResult.OK Then
path = IO.Path.GetDirectoryName(openFileDialog1.FileName)
nomeFile = IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName)
nomeFileTxt = IO.Path.GetFileName(openFileDialog1.FileName)
Else
' How can go back the program start (Form1 with the button)???
End If
End Sub

Public Function GetNomeFile() As String
Return nomeFile
End Function

Public Function GetPath() As String
Return path
End Function

End Class


Imports System.IO
Public Class FilePan
Dim path As String
Dim nomeFilePan As String

Public Sub SetFilePan(ByVal _nomeFile As String, ByVal _path As String)

path = _path
nomeFilePan = path.Replace("1319", "panasonic\") + _nomeFile + ".pan"

If File.Exists(nomeFilePan) Then
File.Delete(nomeFilePan)
End If
End Sub
End Class

最佳答案

有很多方法可以做你想做的事。如果你想用你当前的结构来做,你可以尝试:

Public Function SetFileTxt() as Boolean
Dim openFileDialog1 As New OpenFileDialog() With
{
.InitialDirectory = "",
.Filter = "Txt file|*txt",
.FilterIndex = 1,
.RestoreDirectory = True,
.Title = "Seleziona file"
}
If openFileDialog1.ShowDialog() = DialogResult.OK Then
path = IO.Path.GetDirectoryName(openFileDialog1.FileName)
nomeFile = IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName)
nomeFileTxt = IO.Path.GetFileName(openFileDialog1.FileName)
return True
Else
return False
End If
End Function

如果未在对话框中单击“确定”,这将返回 bool 值 false。然后将 .SetFileTxt() 放在 if 语句中。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If _fileTxt.SetFileTxt() Then
CreaPan.SetFilePan(_fileTxt.GetNomeFile(), _fileTxt.GetPath())
End If
End Sub

关于vb.net - 在 openFileDialog 上按下 Cancel 按钮时,如何才能没有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com