Search/select database with C#

Asked

Viewed 139 times

0

I have a form with a button and a simple datagridView, but my problem is that I have to search my file in ". mdb" (Access database) on the computer, so it will be shown in the datagridView then the question:

When clicking the button, I want an openFileDialog to appear, where the user looks for the database, so when he selects the file populate the datagridView with the information of the database he selected.

Is there any way to do it?

I tried to use a model that derpirscher (US Stack overflow user) advised me, would be more or less like this:

private void button1_Click(object sender, EventArgs e)
{
  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)) {
     //..realiza as query's
    }

  }

}
  • Post what you’ve tried to do.

  • The code is almost ready, just include the query query in the indicated location, some error found?

  • To popular your grid with the data you will have to create a method for reading the file.

  • what I am in doubt is how I will trigger in the click of "open" to call the file the connections with oledb, how I can transform @"Provider=Microsoft.Jet.OLEDB.4.0;" +
 "Data Source=C:\myPath\myFile.mdb;" + 
 "Persist Security Info=True;" +
 "Jet OLEDB:Database Password=myPassword;" something dynamic, since the database should be searched on the pc

1 answer

0


Matt, your connectionstring is already dynamic, it takes the database path through the dbfile variable (which gets dlg.Filename). From there, whenever you need connectionstring use its variable.

  • helped a lot (for lack of attention I didn’t realize that I was really separated) ! disassembled all the items in the string (delimited by " ") and worked, now I have to make the connection go correctly, would have any idea?

  • When you mount the string with the string. Format, is closing the string before "Persist Security Info", it is part of the connectionstring. Try string connectstring = string.format("Provider=Microsoft.ACE.OLEDB.12. 0;Data Source={0};Persist Security Info=False;", dbfile); (changing the place quotes).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.