简体   繁体   English

删除行后,DataGridView中的Access数据库未更新

[英]access database not updating in DataGridView after deletion of a row

I am developing an Application for Computers store and i need an option to delete a product from the store , so i created a DataGridView and the data source of it was the database file of access. 我正在开发“计算机应用程序商店”,我需要一个从商店中删除产品的选项,因此我创建了一个DataGridView ,它的数据源是access的数据库文件。

when i debugged for the first time , i deleted a row and it updated in the DataGridView and Updated in the Access database file , but when i exit the app an re-debug , the list shows the deleted row one more time (Althought it's not showen in the access database file). 当我第一次调试时,我删除了一行,并在DataGridView中对其进行了更新,并在Access数据库文件中进行了更新,但是当我退出应用程序重新调试时,该列表将再次显示已删除的行(尽管不是这样)在访问数据库文件中显示)。

and it also causes error (SystemNullReferenceException) now when i delete any row 当我删除任何行时,它现在也导致错误(SystemNullReferenceException)

Am using OleDb provider. 我正在使用OleDb提供程序。

here is my code: 这是我的代码:

namespace CompStore
{
    public partial class ProductRemove : Form
    {
        private string str = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=J:\C#\CompStore\Store.accdb";
        OleDbConnection con;
        OleDbCommand com;


        public ProductRemove()
        {
            con = new OleDbConnection(str);
            InitializeComponent();
        }

        private void ProductRemove_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'storeDataSet.Products' table. You can move, or remove it, as needed.
            this.productsTableAdapter.Fill(this.storeDataSet.Products);

        }




        private void button1_Click_1(object sender, EventArgs e)
        {
            con.Open();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow delrow = dataGridView1.Rows[i];
                if (delrow.Selected == true)
                {

                    try
                    {
                        com.CommandText = "DELETE  FROM Products WHERE ProductID=" + dataGridView1.Rows[i].Cells[0].Value + "";
                        com.Connection = con;
                        int count = com.ExecuteNonQuery();
                    }
                    catch (Exception ex) { MessageBox.Show(ex.ToString()); }
                    dataGridView1.Rows.RemoveAt(i);
                }
            }


            con.Close();
        }


    }
}

I think the issue is that you are removing items as you move through them. 我认为问题在于您在移动项目时正在删除项目。 what may help is to create a list of id's to remove. 可能有帮助的是创建要删除的ID列表。 then at the end remove them all and rebind the grid. 然后最后将它们全部删除并重新绑定网格。

something like this: 像这样的东西:

            var idsToRemove = new List<int>();
            var rowsToRemove = new List<int>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow delrow = dataGridView1.Rows[i];
                if (delrow.Selected == true)
                {

                    try
                    {
                        //com.CommandText = "DELETE  FROM Products WHERE ProductID=" + dataGridView1.Rows[i].Cells[0].Value + "";
                        //com.Connection = con;
                        //int count = com.ExecuteNonQuery();
                        idsToRemove.add(dataGridView1.Rows[i].Cells[0].Value);
                    }
                    catch (Exception ex) { MessageBox.Show(ex.ToString()); }
                    //dataGridView1.Rows.RemoveAt(i);
                    //^this changes the list length throws things off
                                            rowsToRemove.Add(i);
                }
            }

            con.Open();
            com.CommandText = "DELETE  FROM Products WHERE ProductID in(" + string.join(',', idsToRemove.ToArray() + ")";
            con.Close();

            //now rebind your grid so it has the right data

                            // or for each row to remove dataGridView1.Rows.RemoveAt(arow)

hope this helps 希望这可以帮助

I think this code might work for solving your DataGridView problem (I use this code for myself): 我认为这段代码可能可以解决您的DataGridView问题(我自己使用了这段代码):

private void button1_Click_1(object sender, EventArgs e)
{
    foreach (DataGridViewRow item in this.datagridview1.SelectedRows)
    {
        datagridview1.Rows.RemoveAt(item.Index);
    }
}

(Writing this complete foreach code snippet will be better than just writing the statement inside it, make sure this code snippet is outside the for loop!) (编写完整的foreach代码段比仅在其中编写语句要好,请确保此代码段在for循环之外!)

You can write this code before writing the code for deleting the row(s) of the database. 您可以在编写用于删除数据库行的代码之前编写此代码。 Hope this helps for you too. 希望这对您也有帮助。 Send me a response when you(or anyone else) try this code to tell if it worked or not. 当您(或其他任何人)尝试使用此代码来判断其是否有效时,请给我答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM