i have been doing like the code below, but why when i clicking the "delete" button, it is delete all records in the datagridview, but it does not updating to the database. And, how do i make only the selected row that has been selected by the user that gonna be deleted. I already can retrieve the "ID", which is that "ID" i gonna use as WHERE clause in my query.

Here is the code:

deleteButton.Click += new System.EventHandler(this.DeleteRecord);

 private void DeleteRecord(object sender, EventArgs e)
        {
            int i = dataGridView.SelectedCells[0].RowIndex;
            string strID = dataGridView.Rows[i].Cells[0].Value.ToString();

            if (fifthForm.comboBox1.Text == "English")
            {
                using (OleDbConnection conn = new OleDbConnection(connectionString))
                {
                    string query = "DELETE FROM [Record] WHERE [ID] = @ID";
                    conn.Open();

                    using (OleDbCommand cmd = new OleDbCommand(query, conn))
                    {
                        cmd.Parameters.Add("ID", System.Data.OleDb.OleDbType.Integer);

                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
                        {
                            DataTable ds = new DataTable();
                            cmd.Parameters["ID"].Value = strID;
                            adapter.Update(ds);
                            dataGridView.DataSource = ds;
                            cmd.ExecuteNonQuery();
                        }
                    }

                    conn.Close();
                }
            }
       }

Could anyone help me? Thanks

Recommended Answers

All 4 Replies

So from what I read above the code, you want to delete just a single record?

I don't see you specifying that within the code unless I missed it(Terrible sight today) so that's what I suggest you do if you still wish for the code tell me in your reply as I am not on the computer currently

yes, when the user select one of the data in datagridview and click "delete" button, the data will be removed from the datagridview as well as in the database (or you could say the data will be removed both from the datagridview and the database). Thanks.

OleDB uses the '?' character for parameters, not the SQL Server '@ID' type parameters and assigns them in order from left to right.

So your SQL statement should be "DELETE FROM [Record] WHERE [ID] = ?"

Check out the example on this page.

There is also no reason for line 25.

My friend,
you stated that you are selecting a record from grid. Which control are you using?

Is it a checkbox?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.