C1TrueDBGrid中,将MultiSelect属性设置为MultiSelectEnum.Simple|MultiSelectEnum.Extended,可以支持record selector多行选择。有些用户希望通过点击行使用这个功能,而不想使用record selector。

本文就介绍如何使用鼠标和Ctrl+Shift键选择多行。

首先我们需要手动的处理多行的选择,因此我们需要取消自动选择行,这个需要在SelChange事件里设置CancelEventArgs的Cancel属性为True。代码如下:

void c1TrueDBGrid1_SelChange(object sender, C1.Win.C1TrueDBGrid.CancelEventArgs e)
{
  e.Cancel = true;
}

 

然后,我们需要RowColChange事件里尝试操作SelectedRows集合。每次Focus移到新的单元格的时候,我们都需要考虑是否按下了Ctrl/Shift键,并更新SelectedRows集合。假设ctrl键被按下,我们将设法添加或删除点击行,这主要看它是否存在于SelectedRows集合里。对于Shift键来说,如果它被按下,我们将选择SelectedRows集合里的第一行到当前被点击行之间的所有行。

代码如下:

//Multiple Selection code will be handled here based on Ctrl or Shift key
void c1TrueDBGrid1_RowColChange(object sender, C1.Win.C1TrueDBGrid.RowColChangeEventArgs e)
{
   //Control key is pressed : Add or delete the row from selection depending on whether the row is in SelectedRows Collection
 if (((Control.ModifierKeys & Keys.Control) != 0) && c1TrueDBGrid1.MultiSelect != C1.Win.C1TrueDBGrid.MultiSelectEnum.None)
 {
   if (c1TrueDBGrid1.SelectedRows.IndexOf(c1TrueDBGrid1.Row) > -1)
    {
      c1TrueDBGrid1.SelectedRows.RemoveAt(c1TrueDBGrid1.SelectedRows.IndexOf(c1TrueDBGrid1.Row));
    }
  else
   {
     c1TrueDBGrid1.SelectedRows.Add(c1TrueDBGrid1.Row);
   }
}
else //Shift key is pressed : selects all rows between the first selected row in selected row collection and the currently clicked row:
 {
  if (((Control.ModifierKeys & Keys.Shift) != 0) && c1TrueDBGrid1.MultiSelect != C1.Win.C1TrueDBGrid.MultiSelectEnum.None)
   {
     int SelRowStartindex = c1TrueDBGrid1.SelectedRows[0];
     c1TrueDBGrid1.SelectedRows.Clear();
     c1TrueDBGrid1.SelectedRows.Add(SelRowStartindex);
     if (c1TrueDBGrid1.SelectedRows.Count > 0)
      {
        if (c1TrueDBGrid1.SelectedRows[0] > c1TrueDBGrid1.Row)
          {
           for (row = c1TrueDBGrid1.SelectedRows[0]; row >= c1TrueDBGrid1.Row; row += -1)
            {
               if (c1TrueDBGrid1.SelectedRows.IndexOf(row) > -1)
                {
                  cTrueDBGrid1.SelectedRows.RemoveAt(c1TrueDBGrid1.SelectedRows.IndexOf(row));
                }
              c1TrueDBGrid1.SelectedRows.Add(row);
             }
          }
        else
          {
          for (row = c1TrueDBGrid1.SelectedRows[0]; row <= c1TrueDBGrid1.Row; row++)            {             if (c1TrueDBGrid1.SelectedRows.IndexOf(row) > -1)
              {
                c1TrueDBGrid1.SelectedRows.RemoveAt(c1TrueDBGrid1.SelectedRows.IndexOf(row));
              }
             c1TrueDBGrid1.SelectedRows.Add(row);
           }
         }
      }
   }
   else
   {
      c1TrueDBGrid1.SelectedRows.Clear();
      c1TrueDBGrid1.SelectedRows.Add(c1TrueDBGrid1.Row);
   }
 }
}

 

运行起来,效果如下图所示:

 

本文源代码如下:

Multiple-Selection-C.zip (34.58 kb)