Wednesday, April 6, 2011

Preventing Edits to specific rows in DataGridView

I want to prevent the user from editing or deleting the first three rows of a datagridview.

How can I do this?

From stackoverflow
  • One way to do it is to capture _CellBeginEdit event, check if any edits on the targeted row are allowed, and cancel event if no edits allowed:

    private void dataGridViewIndexesSpecs_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {

            if (e.RowIndex <= 3)
                e.Cancel = true;
    
        }
    
    Malfist : will that prevent them from deleting it too?
    Malfist : It does not prevent deletion
  • Solution:

    private void dataGridView3_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {
        if (e.RowIndex < 3) {
            e.Cancel = true;
        }
    }
    
    private void dataGridView3_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) {
        if (e.Row.Index < 3) {
            e.Cancel = true;
        }
    }
    

0 comments:

Post a Comment