Inno
Inno

Reputation: 2567

DataGridView: How to enable multi row select but disable multi cell select?

I'm looking for a way to enable multi row select in a DataGridView-Control but disable multi cell select.

What I've tried so far:

It's for an export function: The user should be able to export selected rows to a file but in general he should not be able to select more than one cell (for copy & paste etc.).

Regards,

inno

----- [UPDATE] -----

Here's my implementation. Works fine (comments removed for compactness):

using System.Windows.Forms;

namespace YourAmazingNamespace
{
    public partial class SpecialSelectDataGridView: DataGridView
    {
        public SpecialSelectDataGridView()
        {
            InitializeComponent();
        }

        protected override void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
        {
            ResetSelectedCells();

            base.SetSelectedCellCore(columnIndex, rowIndex, selected);
        }

        void ResetSelectedCells()
        {
            foreach (DataGridViewCell cell in SelectedCells) {
                base.SetSelectedCellCore(cell.ColumnIndex, cell.RowIndex, false);
            }
        }
    }
}

Multiple rows are selected through MultiSelect = true (default value) and currently selected cells are resetted by calling ResetSelectedCells() before selecting the new one.

HTH, thanks and regards,

inno

Upvotes: 3

Views: 10839

Answers (1)

Pop Catalin
Pop Catalin

Reputation: 62960

You could override SetSelectedRowCore or SetSelectedCelCore and perform your custom selection.

MSDN Quote:

The DataGridView control uses this method whenever it changes the selection state of a cell. The selection state changes without regard to the current SelectionMode property value, and without changing the CurrentCell property value. This is useful when you want to implement your own selection modes

Of course this means you will have to use an derived datagrid and not the standard one.

Upvotes: 1

Related Questions