la base de datos de acceso no se actualiza en DataGridView después de la eliminación de una fila

I am developing an Application for Computers store and i need an option to borrar a product from the store , so i created a DataGridView y fuente de datos of it was the database file of 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).

and it also causes error (SystemNullReferenceException) now when i delete any row

Am using OleDb provider.

aquí está mi código:

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();
        }


    }
}

preguntado el 22 de mayo de 14 a las 21:05

2 Respuestas

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. then at the end remove them all and rebind the grid.

algo como esto:

            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)

espero que esto ayude

contestado el 22 de mayo de 14 a las 21:05

how do i rebind my grid ? - GabourX

how did you get the data in there in the first place? you could keep a list of the index to remove too, not the cleanest but will work for now - trabajoabyte

altered my answer to speak to keeping the list of rows to remove too - trabajoabyte

I didn't write code to bind it , visual studio opened a box when i dragged the datagridview to the form , and i binded the tables of the access file - GabourX

@GabourX, you can probably say dataGridView1.DataBind() - trabajoabyte

I think this code might work for solving your DataGridView problem (I use this code for myself):

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!)

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.

Respondido 04 ago 14, 01:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.