Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Preventing Deselect (Ctrl+Click) in GridRow

4.88/5 (4 votes)
28 Nov 2013CPOL 16.3K  
Tip for preventing deselection of rows in DataGridView

Introduction

This tip will help in preventing deselection of rows in the DataGridView control. Many would have come across this situation where-in always any random or specific row should be selected in the GridView.

Using the Code

The simple way to do that is to include the below line of code in the DataGridView CellMouseDown event. If you don't need right click option in the DataGridView control, then add this:

C#
// if (e.Button == MouseButtons.Left)

Otherwise, remove it from the below code:

C#
// GridViewCell Mouse Down Event
private void GridViewCellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
 // Check for Modifiers Key(CNTRL Key)
 if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
 { 
  if (e.Button == MouseButtons.Left)
  {
        CustomerGridView.ClearSelection();
  }
 }
}

Hope this tip will help you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)