0

我正在处理一项作业,我需要使用 OpenFileDialog 类来选择一个 .txt 文件并将该文件名属性返回给一个名为 GetFileName() 的函数

现在这是我的按钮单击代码:

    Private Sub 
    btnSelectFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectFile.Click

End Sub

我很困惑如何将我选择的文件放入我的函数中。这是我的功能的代码。

     Private Function GetFileName() As String

     Dim OpenDonorList As New OpenFileDialog

    OpenDonorList.Filter = "txt files (*.txt)|*.txt"
    OpenDonorList.Title = "Save File As"
    OpenDonorList.InitialDirectory = "C:\"
    OpenDonorList.RestoreDirectory = True

    DialogResult = OpenDonorList.ShowDialog

    If DialogResult = Windows.Forms.DialogResult.OK Then



    Return ?
    End Function

如何将我的 OpenDonorList .txt 文件添加到我的 GetFileName() 函数中?

谢谢!

4

3 回答 3

1

您已经拥有了大部分代码,您所要做的就是使用FileName属性返回选定的文件:

If DialogResult = Windows.Forms.DialogResult.OK Then
    Return OpenDonorList.FileName
End If

我还会将此行添加到打开文件窗口的设置中,以确保只能选择一个文件:

OpenDonorList.Multiselect = False
于 2013-11-06T22:44:30.433 回答
1

在我看来,您不确定如何通过单击按钮调用该函数(我可能错了)。因此,首先,当您调用函数时,它必须始终返回一个值(来自 return 关键字)。

您已经设置了一个显示 OpenFileDialog 的函数 - 那么它应该返回什么值?它应该返回一个路径和文件名。这可以存储在一个字符串变量中。

因此,对您的代码进行一些调整可能会解决它。

这是一个例子:

在你的按钮代码上,你想调用实际的函数加上一个变量来存储路径名(如上面的字符串)简单地:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim thePathName As String = GetFileName()
    MessageBox.Show(thePathName)
End Sub

现在,在要添加返回的函数中。您的 if 语句有问题(如果没有结束)。如果结果正常,则返回路径名。否则返回 null 并调用错误(您可以更改它):

Private Function GetFileName() As String

    Dim OpenDonorList As New OpenFileDialog

    OpenDonorList.Filter = "txt files (*.txt)|*.txt"
    OpenDonorList.Title = "Save File As"
    OpenDonorList.InitialDirectory = "C:\"
    OpenDonorList.RestoreDirectory = True

    DialogResult = OpenDonorList.ShowDialog

    If DialogResult = Windows.Forms.DialogResult.OK Then
        Return OpenDonorList.FileName
    Else
        MessageBox.Show("Error!")
        Return vbNull
    End If

End Function

然后,在按钮代码中,您可以调用另一个例程,该例程使用 thePathName 的值来执行某些操作,例如打开文件进行读取。在上面的示例中,它将只显示一个带有所选文件路径名的消息框。

希望这可以帮助。

于 2013-11-06T22:45:30.900 回答
1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim fileName As String = GetFileName()
    If (String.IsNullOrEmpty(fileName)) Then
        MessageBox.Show("No file was selected.")
    Else
        MessageBox.Show(String.Format("You selected file: {0}", fileName))
    End If
End Sub

Private Function GetFileName() As String
    Dim openDonorList As New OpenFileDialog()
    With openDonorList
        .Filter = "txt files (*.txt)|*.txt"
        .Title = "Save File As"
        .InitialDirectory = "C:\"
        .RestoreDirectory = True
    End With
    Dim result As DialogResult = openDonorList.ShowDialog()
    If result = Windows.Forms.DialogResult.OK Then Return openDonorList.FileName
    Return Nothing
End Function
于 2013-11-06T22:50:54.770 回答