如何使用 OpenFileDialog

How to use OpenFileDialog

我有两个表格 frmChooseDBasefrmMainfrmChooseDBase 用于选择文件(数据库文件)。一旦他选择完数据库,frmMain 将加载从 frmChooseDBase 中选择的数据库。 我该怎么做?任何帮助。 这是我的示例代码:

Public Class frmChooseDBase
    Public sr As String
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            sr = OpenFileDialog1.FileName
            Me.Hide()
            FrmMain.Show()
        End If
    End Sub
End Class

Private Sub FrmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Desktop\'" & frmChooseDBase.sr & "';Extended Properties=Excel 8.0"
        con.Open()


 FillDGView("SELECT [CCCD Loading Database] AS [Transaction Date], [F2] AS [Unit Number], [F3] AS [Category], [F4] AS [Temp Required (C)], [F5] AS [Type Length], [F6] AS [T-State], [F7] AS [Position], [F8] AS [I/B Actual Visit], [F9] AS [Fright Kind] FROM [Loading$]")

    End Sub

如果你只是想加载一个文件,你不需要制作一个新的表格。只需一个按钮或菜单项,上面写着加载数据库。单击它将弹出一个 OpenFileDialog。将 openFileDialog 控件拖到窗体上并为其指定一个有意义的名称 (openFileDialog1...)

openFileDialog1.Title = "Please select a DB file"
openFileDialog1.InitialDirectory = "C:\"
openFileDialog1.Filter = "DB Files|*.extensionHERE"

If openFileDialog1.ShowDialog() = DialogResult.OK then
    'Do things here, the path is stored in openFileDialog1.Filename
    'If no files were selected, openFileDialog1.Filename is ""  
End If

如果您遇到困难或需要快速帮助,有很多使用 openFileDialog 控件的示例。

您甚至不必使用控件:

Dim ofd As OpenFileDialog = New OpenFileDialog
ofd.DefaultExt = "txt"
ofd.FileName = "defaultname"
ofd.InitialDirectory = "c:\"
ofd.Filter ="All files|*.*|Text files|*.txt"
ofd.Title = "Select file"
If ofd.ShowDialog() <> DialogResult.Cancel Then
    MsgBox(ofd.FileName)
End If