简体   繁体   中英

Row not deleting from Database. DataGridView & SQLCE

I'm attempting to delete a selected row from the database and the DataGridView.

The code below seems to work because if I start the program and delete the row it's removed from the data grid. If I reload the program it is still removed from the datagrid. But, if I view the table using the Database Explorer the row is still there. If I refresh the table, and reload the program the deleted row appears.

Any idea why this is happening?

private void button1_Click(object sender, EventArgs e)
    {

        Int32 selectedRowCount = dataAccounts.Rows.GetRowCount(DataGridViewElementStates.Selected);

        if (selectedRowCount > 0)
        {
            using (SqlCeConnection c = new SqlCeConnection(Properties.Settings.Default.snogAccountsConnectionString))
            {
                c.Open();

                for (int i = 0; i < selectedRowCount; i++)
                {
                    using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE id = (@id)", c))
                    {
                        com.Parameters.AddWithValue("@id", dataAccounts.SelectedRows[i].Cells["userID"].Value);
                        com.ExecuteNonQuery();
                    }
                    dataAccounts.Rows.RemoveAt(i);
                }
            }
        }
        else
        {
            MessageBox.Show("Select some rows to delete.");
        }
    }

Are you using a BIGINT for your Primary Key field. I have one table which uses a BIGINT as a primary key and all sorts of odd things happen with that.

You can't just update using the SQL Management Studio GUI edit table facility. It always complains, and you constantly have to use a CAST statement in order to tell the system what kind of data it is, despite the fact that when you do it tells you that this may be unnecessary. BIGINT'S cause a lot of documented problems.

The only way that I can update a record in this table is by using an update T-SQL statement.

You could also try formatting the code thus:

                using (SqlCeCommand com = new SqlCeCommand("DELETE FROM accounts WHERE id ="+ dataAccounts.SelectedRows[i].Cells["userID"].Value.ToString(), c))
                {
                    com.ExecuteNonQuery();
                }

of course, this will throw an error if the wrong type of data is passed, but at least you should know then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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