【问题标题】:C# Don't allow DataGridViewCheckBoxColumn to remove selectionC# 不允许 DataGridViewCheckBoxColumn 删除选择
【发布时间】:2016-10-18 14:12:37
【问题描述】:

我有一个 DataGridView,第一列是 DataGridViewCheckBoxColumn。 我将 SelectionMode 设置为 FullRowSelect。 我已将 MultiSelect 设置为 True。

我希望能够选择多行,然后检查第一列。这将选中或取消选中当前选中的所有复选框;但是,当我这样做时,选择会被删除,并且只会选择我单击其复选框的行。

换句话说,我不想在单击复选框单元格时删除选择。

【问题讨论】:

    标签: c# datagridview selection


    【解决方案1】:

    确保将 EditMode 设置为 EditProgrammatically

    public class DataGridViewUsers : DataGridView
    {
        protected override void OnMouseDown(MouseEventArgs e)
        {
    
            int col = HitTest(e.X, e.Y).ColumnIndex;
            int row = HitTest(e.X, e.Y).RowIndex;
    
            if (col == -1 || row == -1)
            {
                base.OnMouseDown(e);
                return;
            }
    
            // Make sure we select the row we are clicking on
            if (!Rows[row].Selected)
                base.OnMouseDown(e);
    
            if (col == 0 && Rows[row].Selected)
            {
                DataGridViewCheckBoxCell cell = Rows[row].Cells[0] as DataGridViewCheckBoxCell;
                bool bIsSelection = cell != null && cell.Value != null && (bool)cell.Value;
    
                for (int i = 0; i < SelectedRows.Count; i++)
                {
                    SelectedRows[i].SetValues(!bIsSelection);
                }
            }
            else
            {
                // Process normally
                base.OnMouseDown(e);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我不熟悉 DataGridView,因为我只是使用 DevExpress-Framework,但我希望您必须在单击复选框时保存选择。稍后您可以恢复选择。

      List<DataRow> tempSelection = new List<DataRow>();
      foreach (DataRow row in dataGridView.SelectedRows)
      {
        tempSelection.Add(row);
      }
      
      //click your checkbox and do some stuff
      
      foreach (DataRow row in tempSelection)
      {
         row.Selected = true;
      }
      

      但是您认为单击一个复选框并检查多个值是否直观?也许使用带有按钮“CheckSelection”的 contextMenu 更直观。想想看;)

      【讨论】:

      • 在调用 CellContentClick 时,多项选择已经消失。检查所选行的所有复选框很直观。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多