我已将数据从数据库加载到名为 myDS 的数据集中。 myDS 包含多个表格。然后我将其中一个表(名为库存)绑定到名为 dataGridViewInventory 的datagridview中,一切正常。 但是,当我尝试在Inventory表中搜索并且结果绑定到datagridview dataGridViewInventory但它看起来是空的。
以下是搜索和绑定的代码:
DataRow[] filteredRows =
myDS.Tables["Inventory"].Select(string.Format("Make LIKE '%{0}%'", txtMake.Text.Trim()));
DataSet tempTaskDS = new DataSet("tempCars");
//tempTaskDS.Tables.Add("TempInv");
DataTable DataTable2 = new DataTable("TempInv");
// This makes the new DataTable have the same columns as the existing DataTable.
DataTable2 = myDS.Tables["Inventory"].Clone();
foreach (DataRow r in filteredRows)
{
DataTable2.ImportRow(r);
}
tempTaskDS.Tables.Add(DataTable2);
dataGridViewInventory.DataSource = tempTaskDS.Tables["TempInv"];
有人能告诉我出错了吗?
答案 0 :(得分:0)
找到解决方案: 不需要使用临时数据集,只需使用BindingSource并将数据表绑定到它,然后将BindingSource绑定到datagridview。代码如下:
DataRow[] filteredRows =
myDS.Tables["Inventory"].Select(string.Format("Make LIKE '%{0}%'", txtMake.Text.Trim()));
DataTable DataTable2 = new DataTable("TempInv");
// This makes the new DataTable have the same columns as the existing DataTable.
DataTable2 = myDS.Tables["Inventory"].Clone();
foreach (DataRow r in filteredRows)
{
DataTable2.ImportRow(r);
}
BindingSource bSource = new BindingSource();
bSource.DataSource = DataTable2;
dataGridViewInventory.DataSource = bSource;