在问之前,我在互联网上做了很多搜索,但没有找到我的问题的答案。 我有一个带有按钮和两个类的表单。 当我按下窗体上的按钮时,会打开一个对话框,从磁盘中选择一个file.txt。 如果按下“打开”按钮,程序将继续正确执行代码写入的操作。 如果我按下取消按钮,程序会出现错误:System.NullReferenceException:'引用未在对象实例上设置的对象。'路径没什么。 (在类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
答案 0 :(得分:1)
有很多方法可以做你想要的。如果您想使用当前结构,可以尝试:
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
如果未在对话框中单击“确定”,则返回false的bool。 然后将.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