Search code examples
c#databaseoledbdatagridviewcombobox

Selecting table from database with combobox and populating datagridview-can't get it to work


OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT nazivMaterijala FROM popisMaterijala",     con);
DataTable dt = new DataTable();
da2.Fill(dt);
BindingSource bndSource2 = new BindingSource();
bndSource2.DataSource = dt;
this.comboBox1.DataSource = bndSource2;
comboBox1.DisplayMember = "nazivMaterijala";
comboBox1.ValueMember = "nazivMaterijala";

with this part of code i get the table names into combobox

private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        OleDbConnection con = new OleDbConnection(connectionString);
        OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT * FROM ["     +this.comboBox1.SelectedValue.ToString() +"]", con);
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        da2.MissingSchemaAction = MissingSchemaAction.AddWithKey;
        da2.Fill(dt);
        this.dataGridView1.DataSource = dt; 
    }

after selecting something from combobox1 it should populate the gridview with data from selected table, but can't get it to work

This is the message i get when I try to run it: The Microsoft Access database engine cannot find the input table or query 'System.Data.DataRowView'. Make sure it exists and that its name is spelled correctly.


Solution

  • Try to use the SelectionChangeCommitted instead. The SelectedValueChanged event is raised during binding and in this context the actual values DisplayMember and ValueMember are not properly set

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        // Better to be safe here.....
        if (this.comboBox1.SelectedValue == null)
            return;
    
        using(OleDbConnection con = new OleDbConnection(connectionString))
        using(OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT * FROM ["     +this.comboBox1.SelectedValue.ToString() +"]", con))
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            da2.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            da2.Fill(dt);
            this.dataGridView1.DataSource = dt; 
        }
    }
    

    See also this question for a better explanation of the problem