如何在 DataGridViewRow 中捕获鼠标,使其仅在行内移动

How can I capture the mouse in a DataGridViewRow, so it only moves within the row

我正在编写一个预订应用程序,它利用 DataGridView 列出 Y 轴下方的可用房间以及 X 轴上的可用时间作为列。

我希望用户能够拖动 select 一个时间范围,但一次必须限制为一行。

要么控制网格的突出显示方面,以便在鼠标移动时只突出显示所需的行,要么在行边界内捕获鼠标是我想到的选项。欢迎任何帮助实施这些任务,甚至是处理任务的新方法!

我更愿意使用发生鼠标按下事件的 DataRow 捕获鼠标,不确定是否必须使用剪切矩形来实现此目的。

在此先感谢您的帮助。

可能是更好的写法,但它确实有效。

private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
    {
        if (dataGridView1.SelectedCells.Count > 1)
        {
            //Retrieves the first cell selected
            var startRow = dataGridView1.SelectedCells[dataGridView1.SelectedCells.Count - 1].RowIndex;

            foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
            {
                if (cell.RowIndex != startRow)
                {
                    cell.Selected = false;
                }
            }
        }
    }

作为对 CellStateChanged 事件代码的改进,可以使用以下代码。

private void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
{
  if ((e.StateChanged == DataGridViewElementStates.Selected) && // Only handle it when the State that changed is Selected
      (dataGridView1.SelectedCells.Count > 1))
  {
    // A LINQ query on the SelectedCells that does the same as the for-loop (might be easier to read, but harder to debug)
    // Use either this or the for-loop, not both
    if (dataGridView1.SelectedCells.Cast<DataGridViewCell>().Where(cell => cell.RowIndex != e.Cell.RowIndex).Count() > 0)
    {
      e.Cell.Selected = false;
    }

    /*
    foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
    {
      if (cell.RowIndex != e.Cell.RowIndex)
      {
        e.Cell.Selected = false;
        break;  // stop the loop as soon as we found one
      }
    }
    */
  }
}

此 for 循环的不同之处在于使用 e.Cell 作为 RowIndex 的参考点,因为 e.Cell 是用户选择的单元格,设置 e.Cell.Selectedfalse 而不是 cell.Selected 最后是 for 循环中的 break; 因为在第一个 RowIndex 不匹配之后,我们可以停止检查。