我正在处理分配,我需要使用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()函数?

谢谢!

有帮助吗?

解决方案

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

您已经设置了一个显示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 statement存在问题(无终止)。如果结果可以,则返回路径名。否则返回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

在按钮代码中,您可以调用另一个使用Pathname值进行操作的例程,例如打开文件读取。在上面的示例中,它将仅显示一个带有路径名的消息框中的“选定文件”。

希望这可以帮助。

其他提示

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

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

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

OpenDonorList.Multiselect = False
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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top