Tuesday, October 02, 2007

Excel-like select all in a DataGrid

Clicking on the top-left cell in Excel selects the whole worksheet, which always seemed like a good use of an otherwise useless cell. So I've done the same with the DataGird-derived control I've been using in one of my apps. It's pretty damn simple to implement, but for the lazy amongst you, here's some code.

    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);
      HitTestInfo hitInfo = HitTest(PointToClient(Cursor.Position));
      if ((hitInfo.Column == -1) && (hitInfo.Row == -1))
      {
        SelectAll();
      }
    }

No comments: