Friday, October 19, 2007

Improved Excel-like select all in a DataGrid

My first attempt at this worked mostly but if the user clicked anywhere in the grid that wasn't a cell, the whole grid would be selected, which wasn't what I was after. So here's an improved version which will only select all when the user clicks in the top left cell.

    public void SelectAll()
    {
      BindingManagerBase bm = BindingContext[DataSource];
      for (int i = 0; i < bm.Count; i++)
      {
        Select(i);
      }
    }

    protected override void OnClick (EventArgs e)
    {
      base.OnClick(e);
      Point client = PointToClient(Cursor.Position);
      HitTestInfo hitInfo = HitTest(client);
      if ((hitInfo.Column == -1) && (hitInfo.Row == -1))
      {
        if (client.X < TableStyles[0].GridColumnStyles[0].Width)
          if (client.Y < TableStyles[0].PreferredRowHeight)
            SelectAll();
      }
    }

No comments: