我的应用程序通过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);
}
}
有什么想法吗?
发布于 2018-08-28 09:47:25
在辅助搜索中,而不是:
dataGridView2.DataSource = ds;
尝试:
DataTable combinedData = (DataTable)(dataGridView2.DataSource);
combinedData.Merge(ds);
dataGridView2.DataSource = combinedData;
您可能还必须注意避免在新数据源中出现重复项。另外:我没有测试这个解决方案,它只是一个想法。
希望能有所帮助
发布于 2018-08-28 09:40:30
你可以有两个DataTables,比如说dt1
,dt2
和一个合并的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);
}
}
发布于 2018-08-28 09:50:50
您需要使用merge
。这里有一个关于它的教程here
https://stackoverflow.com/questions/52054350
复制