Disable selection of rows in a datagridview

25,395

If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.

If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.

Here's an example:

public class MyDataGridView : DataGridView
{
    protected override void SetSelectedRowCore(int rowIndex, bool selected)
    {
        if (selected && WantRowSelection(rowIndex))
        {
            base.SetSelectedRowCore(rowIndex, selected);
        }
     }

     protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
     {
         if (selected && WantRowSelection(rowIndex))
         {
            base.SetSelectedRowCore(rowIndex, selected);
          }
     }

     bool WantRowSelection(int rowIndex)
     {
        //return true if you want the row to be selectable, false otherwise
     }
}

If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.

Share:
25,395
Niki
Author by

Niki

Updated on February 14, 2020

Comments

  • Niki
    Niki over 4 years

    I want to disable the selection of certain rows in a datagridview.

    It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)

    Thankx,

  • The King
    The King about 14 years
    A Solution that works... But for this I think we need to create a Class which extends datagridview control... Am I Right... Don't we have a solution that works on current datagridview class
  • hila shmueli
    hila shmueli almost 14 years
    I would like to ask if there is a facility to only highlight certain column even if the row is set as selected.
  • Sev09
    Sev09 over 10 years
    @szevvy, can you explain further? I'm in need of this answer right now, as well.
  • szevvy
    szevvy over 10 years
    @Sev09 - No problem, added code sample + description of how to use it.
  • Little Endian
    Little Endian about 10 years
    I think this will still unselect whatever is currently selected. Is there a way to both prohibit selection of certain cells and (in that case) keep current selection?
  • Jim Balkwill
    Jim Balkwill over 9 years
    Cool. To also support deselection, just use if (WantRowSelection(rowIndex))