views:

41

answers:

1

Hello everyone,

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:

  • DataGridView.MultiSelect = true allows to select multi rows and cells
  • ClearSelection() in DataGridView_CellMouseClick-Event and re-select the last selected cell doesn't look very nice (you see the old cell deselect and then the new cell select; SuspendLayout() and ResumeLayout() doesn't help)
  • DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect is not an option: If the user clicks a cell, it should only this cell get selected

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

+1  A: 

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.

Pop Catalin
Thank you very much!
Inno