Question

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.

Was it helpful?

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

OTHER TIPS

What I think is happening is that you are binding your combobox to the Datarows of your dataset returned from the first query. So when you do a toString on the selected value you are just outputting System.Data.DataRowView. You need to cast your selected Item to System.Data.DataRowView, then find the correct column in it that contains the TableName and pass that into your second query. Something like this. Also Keep in mind if nothing is selected you need to check to make sure selectedItem is not null.

DataRowView dView = (DataRowView)this.comboBox1.SelectedItem;
OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT * FROM ["     + dView.Row["ColumnName that contains TableName"].ToString() +"]", con);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top