0

I'm trying to get a combobox dropdown to display tables in datagridview from database, but I don't know how to do it, I can see example and explanation how to display only one table.

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection ();
        conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.4.0;Data     Source=|DataDirectory|\\Manager.accdb;Persist Security Info=True";
        OleDbCommand cmd = new OleDbCommand ("SELECT  Emplyee, Tasks, Projects from Manager");

        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        adapter.Fill(dt, "Manager");  
    }
Dan Teesdale
  • 1,823
  • 15
  • 26
user2386687
  • 129
  • 1
  • 1
  • 7
  • What's the problem? Errors? Is the dataset empty? Is the datagridview failing to bind? Or is it you aren't doing anything with the data adapter you filled? – Steve Wellens Jun 15 '13 at 17:08

1 Answers1

0

There is no provider named "Provider=Microsoft.ACE.OLEDB.4.0;", perhaps you want to use "Microsoft.ACE.OLEDB.12.0;"

Then, if you want to read all the data from the table names selected in the combobox then your code should be something like this

string conString = "Provider=Microsoft.ACE.OLEDB.12.0;" + 
                   "Data Source=|DataDirectory|\\Manager.accdb;" + 
                   "Persist Security Info=False";
string tableName = comboBox1.SelectedItem.ToString();
using(OleDbConnection conn = new OleDbConnection (conString))
using(OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + tableName + "]", conn))
{
    con.Open();
    using(OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
    {
        DataSet ds = new DataSet();
        adapter.Fill(ds, tableName);  
        dataGridView.DataSource = ds.Tables[0];
    }
}

Please, pay attention to the tablenames inserted in your combobox. Having the build of the sql command text made by string concatenation you have a very dangerous situation. Do not let the user inser these names, but select them yourself. If you have a malicious user it could mount an Sql Injection attack

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286