将两个查询合并到一个数据网格视图中

Combine two queries in one datagridview

我的应用程序通过 openfiledialog 连接到 excel 文件。我有两个搜索,主要搜索和次要搜索。我想在一个数据网格视图中得到他们的结果。我的代码(主要搜索):

private void searchbtn_Click(object sender, EventArgs e)
{
    try
    {
        string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
        OleDbConnection conn = new OleDbConnection(connStr);
        OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + testcb.SelectedItem.ToString() + "$] where [" + comboBox1.SelectedItem.ToString() + "] = '" + textBox5.Text + "'", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);
        dataGridView2.DataSource = dt;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

二次搜索:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
        OleDbConnection conn = new OleDbConnection(connStr);
        OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + testcb.SelectedItem.ToString() + "$] where [" + addcb.SelectedItem.ToString() + "] = '" + addtb.Text + "'", conn);
        DataTable ds = new DataTable();
        da.Fill(ds);
        dataGridView2.DataSource = ds;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

有什么想法吗?

您可以有 2 个 DataTables 让我们说 dt1dt2 和一个合并的 dtAll。然后您可以合并 2 并将其设置为 DataSource

private UpdateDataSource()
{
    dataGridView2.Rows.Clear();
    dataGridView2.Refresh();
    dtAll.Clear();

    if(dt1 == null && dt2 != null)
    {
        dtAll = dt2;
    }
    else if(dt2 == null && dt1 != null)
    {
        dtAll = dt1;
    }
    else if(dt1 != null && dt2 != null)
    {
        dtAll = dt1.Copy();
        dtAll.Merge(dt2);
    }
    else
    {
        dtAll = null;
    }
    dataGridView2.DataSource = dtAll;
}

您的事件处理程序应该变成这样:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
        OleDbConnection conn = new OleDbConnection(connStr);
        OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + testcb.SelectedItem.ToString() + "$] where [" + addcb.SelectedItem.ToString() + "] = '" + addtb.Text + "'", conn);
        dt2.Clear();
        da.Fill(dt2);
        UpdateDataSource();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

在二次搜索中,代替:

dataGridView2.DataSource = ds;

尝试:

DataTable combinedData = (DataTable)(dataGridView2.DataSource);
combinedData.Merge(ds);
dataGridView2.DataSource = combinedData;

您可能还需要注意避免新数据源中出现重复项。另外:我没有测试这个解决方案,它只是一个想法。

希望对您有所帮助

您需要使用 merge。有一个教程here