Search code examples
vb.netwinformsopenfiledialog

How to use OpenFileDialog


I have two forms named frmChooseDBase and frmMain. frmChooseDBase is for choosing a file(a database file). Once he's done choosing the database, frmMain will load the database chosen from frmChooseDBase. How can I do dat? any help. Here's my sample codes:

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

Solution

  • If you just want to load a file, you don't need to make a new form. Just have a button or menu item that says load DB. Clicking that will pop an OpenFileDialog. Drag an openFileDialog control onto the form and give it a meaningful name (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
    

    There are plenty of examples for using the openFileDialog control if you get stuck, or need quick help.