How do you delete rows from a datagridview.
I have a delete button to the right in the datagridview. I want to know how to delete a single row by clicking the delete button.

Recommended Answers

All 7 Replies

First create delete button in the grid

//I prefer to use the wizard to generate the delete button 
private System.Windows.Forms.DataGridViewButtonColumn Column1;
this.Column1.HeaderText = "delete";
            this.Column1.Name = "Column1";
            this.Column1.Text = "delete";
            this.Column1.UseColumnTextForButtonValue = true;
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 4)// created column index (delete button)
            {
                dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
                //commit the changes!
            }
        }

I did the way you told me but when i Click the delete button nothing happens.

And what is the 4 for in this code.

if (e.ColumnIndex == 4)// created column index (delete button)

created column index (delete button)

You can do it in a simple way, that is right click on gridview then a popup menu will appear and delete the row. Here is the code sample..

        if (e.Button == MouseButtons.Right) 
        {
            this.dataGridView1.Rows[e.RowIndex].Selected = true; 
            this.rowIndex = e.RowIndex;
            this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];
            this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
            contextMenuStrip1.Show(Cursor.Position);
        }

Full Source code...Datagridview Delete

Watson

I'd go with Watsonsimler's suggestion because it reduces the chance of the user accidentally clicking the delete button in a row they don't want to delete.

You can't also have a checkBox cell in every row and a single delete button on your form (not in the data grid view). This will let the user select multiple rows to delete at once. If you use the checkBox option you can add buttons to do other functions such as exporting the selected rows to an Excel document or something like that.

Sorry I went off on one then but it's another option you could think about which could reduce the amount of work you'll need to do if something like that became a requirement in the future.

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.