-1
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";

使用这部分代码,我将表名放入组合框中

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; 
    }

从 combobox1 中选择某些内容后,它应该使用所选表中的数据填充 gridview,但无法使其工作

这是我尝试运行它时收到的消息:Microsoft Access 数据库引擎找不到输入表或查询“System.Data.DataRowView”。确保它存在并且其名称拼写正确。

4

2 回答 2

0

我认为正在发生的事情是您将组合框绑定到从第一个查询返回的数据集的 Datarows。因此,当您对所选值执行 toString 时,您只是输出 System.Data.DataRowView。您需要将所选项目转换为 System.Data.DataRowView,然后在其中找到包含 TableName 的正确列并将其传递到您的第二个查询中。像这样的东西。另外请记住,如果未选择任何内容,则需要检查以确保 selectedItem 不为空。

DataRowView dView = (DataRowView)this.comboBox1.SelectedItem;
OleDbDataAdapter da2 = new OleDbDataAdapter("SELECT * FROM ["     + dView.Row["ColumnName that contains TableName"].ToString() +"]", con);
于 2013-06-24T14:36:05.553 回答
0

尝试改用SelectionChangeCommitted。在绑定期间引发 SelectedValueChanged 事件,在此上下文中,未正确设置实际值 DisplayMember 和 ValueMember

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; 
    }
}

另请参阅此问题以更好地解释该问题

于 2013-06-24T14:36:52.420 回答