开发者

Cannot bind data to dataset when searching from dataset C#?

开发者 https://www.devze.com 2023-03-22 10:15 出处:网络
I have loaded data from the database to the dataset named myDS. myDS contains several tables. Then I bound one of those tables (named Inventory) into the datagridview named dataGridViewInventory and e

I have loaded data from the database to the dataset named myDS. myDS contains several tables. Then I bound one of those tables (named Inventory) into the datagridview named dataGridViewInventory and everything worked fine. However, when I tried to search in the Inventory table and the result bound to the datagridview dataGridViewInventory but it appeared empty.

Here is the code of searching and binding:

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

Can anyone tell me what I have gone wrong, please?


Found solution: DO not need to use a temporary dataset, just use the BindingSource and bind the datatable to it, then bind the BindingSource to the datagridview. The code is below:

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

精彩评论

暂无评论...
验证码 换一张
取 消