0

I have a form with a button and a dataGridView, I know I can open my database with the OleDB connection, but my problem is that I may have to search where my database (a ".mdb" file) is on my computer.

Is there any way that with this button I open a File.Open (to search my database) and then show it on my datagridview ?

MattDAVM
  • 505
  • 3
  • 6
  • 25
  • If you know the data structure of MDB, then yes. Otherwise no. –  Jul 28 '16 at 11:50
  • how may I search it (I'll add the filter only to read the .mdb files) and when I select it I already activate my query to do a `SELECT * FROM mydatabase` and show it on the datagridView – MattDAVM Jul 28 '16 at 11:52
  • Use OleDB, it is easier, then re-inventing OleDB. –  Jul 28 '16 at 11:53

3 Answers3

2

You can use the OpenFileDialog

Here you have an example: http://www.dotnetperls.com/openfiledialog

mnieto
  • 3,744
  • 4
  • 21
  • 37
2

I'm not sure what you mean with 'File.Open', but you could make a OpenFileDialog where the user is able to select the file he wants to open. From this dialog you get a Filename which you can use in your connection string.

OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Database Files|*.mdb";
if (dlg.ShowDialog() == DialogResult.OK) {
    string dbfile = dlg.FileName;
    string connectstring = string.format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}";Persist Security Info=False;, dbfile);

     using (OleDbConnection con = new OleDbConnection(connectstring)) {
         //... do your database operations here
     }

}
derpirscher
  • 14,418
  • 3
  • 18
  • 35
  • saying "file.Open' I meant this situation https://msdn.microsoft.com/en-us/library/b9skfh7s(v=vs.110).aspx – MattDAVM Jul 28 '16 at 12:02
  • 1
    No, you cannot directly open a db file with `File.Open` unless you know the internal structure of that file. That's what OleDb is here for. You would have to reimplement all those things yourself. – derpirscher Jul 28 '16 at 12:05
1

you have to connect the database with Data providers, not open it like a text file. This thread might be useful for you: How to connect to a MS Access file (mdb) using C#?

Community
  • 1
  • 1
Serge Bollaerts
  • 324
  • 2
  • 6