Link to home
Start Free TrialLog in
Avatar of Rahamathulla_J
Rahamathulla_J

asked on

datagridview row deleting

In Datagridview if the user clicks the delete button the rows are deleting? How can i avoid that?
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

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;
    }
}

http://msdn2.microsoft.com/en-us/library/system.windows.forms.datagridview.userdeletingrow.aspx
Why don't you disable deleting rows in that datagridview ?
Avatar of Rahamathulla_J
Rahamathulla_J

ASKER

Is there any property for that if so no problem for me
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial