Live Chat Icon For mobile
Live Chat Icon

How can I make my DataGrid support a single select mode, and not the default multiselect mode

Platform: WinForms| Category: Datagrid

One way to do this is to derive a DataGrid, override its OnMouseDown and OnMouseMove methods. In the OnMouseDown, handle selecting and unselecting in your code without calling the base class if the click is on the header. In the OnMouseMove, don’t call the baseclass to avoid dragging selections. Below is a code snippet for a sample derived DataGrid. You can download a full project (C#, VB).

public class MyDataGrid : DataGrid
{
  private int oldSelectedRow = -1;
  
  protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e)
  {
    //don’t call the base class if left mouse down
    if(e.Button != MouseButtons.Left)
      base.OnMouseMove(e);
  }

  protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
  {
    //don’t call the base class if in header
    DataGrid.HitTestInfo hti = this.HitTest(new Point(e.X, e.Y));
    if(hti.Type == DataGrid.HitTestType.Cell) 
    {
      if(oldSelectedRow > -1)
        this.UnSelect(oldSelectedRow);
      oldSelectedRow = -1;
      base.OnMouseDown(e);
    }
    else if(hti.Type == DataGrid.HitTestType.RowHeader) 
    {
      if(oldSelectedRow > -1)
        this.UnSelect(oldSelectedRow);
      if((Control.ModifierKeys & Keys.Shift) == 0)
        base.OnMouseDown(e);
      else
        this.CurrentCell = new DataGridCell(hti.Row, hti.Column);
      this.Select(hti.Row);
      oldSelectedRow = hti.Row;
    }
  }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.