datagridview row deleting

In Datagridview if the user clicks the delete button the rows are deleting? How can i avoid that?
Who is Participating?
DhaestConnect With a Mentor Commented:
Yes, look at the property's of your datagridview

AllowUserToDeleteRows  --> Gets or sets a value indicating whether the user is allowed to delete rows from the DataGridView.
You need to override the UserDeletingRow event and add code to validate the delete.

The UserDeletingRow fires before the deletion, the UserDeletedRow fires after.
If you set e.cancel = true, the row will not get deleted.

Ask your user with a simple messagebox.

Private Sub DataGridView1_UserDeletingRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles DataGridView1.UserDeletingRow
        If Not MessageBox.Show("Are you sure?", "Deleting", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
            e.Cancel = True
        End If
End Sub

Oops, now an example in c#

private void DataGridView1_UserDeletingRow(object sender,
    DataGridViewRowCancelEventArgs e)
    DataGridViewRow startingBalanceRow = DataGridView1.Rows[0];

    // Check if the Starting Balance row is included in the selected rows
    if (DataGridView1.SelectedRows.Contains(startingBalanceRow))
        // Do not allow the user to delete the Starting Balance row.
        if (e.Row.Equals(startingBalanceRow))
            MessageBox.Show("Cannot delete Starting Balance row!");

        // Cancel the deletion if the Starting Balance row is included.
        e.Cancel = true;
Why don't you disable deleting rows in that datagridview ?
Rahamathulla_JAuthor Commented:
Is there any property for that if so no problem for me
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.