Hey guys,


I need a code that would delete the row from not only from
grid view but also from the table.

I am able to delete the row from grid view but its not getting deleted
from table.

Any suggestions on how to do it.


Regards
Ajinya

Dani AI

Generated

You are removing the UI row but not deleting the corresponding record in the table. As suggested, the key is to use the row’s primary key, not the grid row index. In your loop you build ... where ID = " + i, but i is just the visual index and will not match your table’s ID. Also make sure your OleDbCommand has a connection and use parameters (with OleDb, placeholders are ?). A simple pattern is: delete from the database first, then refresh or remove the UI row.

// Delete selected rows by primary key and then refresh the grid
using (var con = new OleDbConnection(connString))
using (var cmd = new OleDbCommand("DELETE FROM company WHERE ID = ?", con))
{
    con.Open();
    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
        if (row.IsNewRow) continue;
        int id = Convert.ToInt32(row.Cells["ID"].Value); // bind to your PK column
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@p1", id);
        cmd.ExecuteNonQuery();
    }
}
// Requery and rebind your data source here rather than relying on visual removal
LoadCompaniesIntoGrid();

If your DataGridView is data-bound (DataTable/BindingSource), ’s point applies: the adapter must push changes back to the database. Ensure you have a DeleteCommand defined; then mark the bound rows as deleted and call Update on the same DataTable you bound to the grid.

// Configure once at form level
adapter.DeleteCommand = new OleDbCommand("DELETE FROM company WHERE ID = ?", con);
adapter.DeleteCommand.Parameters.Add("@p1", OleDbType.Integer, 0, "ID");

// Later, when deleting
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    ((DataRowView)row.DataBoundItem).Row.Delete();

adapter.Update((DataTable)((BindingSource)dataGridView1.DataSource).DataSource);

Quick checks: set cmd.Connection, use transactions for batch deletes, iterate SelectedRows (not Rows) to avoid index shifting, and rebind the grid after the operation so you can see the change as noted.

Recommended Answers

All 4 Replies

Hi ajinya,
Well, you can store the datakey of the selected row and then delete the row from the table too using that datakey.

hey munnaz,

thanks for your reply.

Let me paste my code :

private void button1_Click(object sender, EventArgs e)
        {
           
            OleDbConnection con = new OleDbConnection(str);
            
            OleDbCommand cmd = new OleDbCommand();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow dr = dataGridView1.Rows[i];
                if (dr.Selected == true)
                {
                    dataGridView1.Rows.RemoveAt(i);
                    try
                    {
                        con.Open();
                        cmd.CommandText = "Delete from company where ID=" + i + "";
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }

I tried deleting row through this code but nothing happened.
Can you help me with the code?


Thanks and Regards
Ajinkya

I think you should recall your grid there. Other wise u cannot know whether your record is deleted in code. Because you are just getting the id of the selected row and making it delete from database but not in ur records. So make a try to recall the grid after ur function has completed..

You miss one line of code from your code just place this line between line 17 and 18

da.Update(ds,"company");

Here da is for data adapter, ds for dataset

Hope it will help you

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.