C# 不允许 DataGridViewCheckBoxColumn 删除选择
C# Don't allow DataGridViewCheckBoxColumn to remove selection
我有一个 DataGridView,第一列是 DataGridViewCheckBoxColumn。
我将 SelectionMode 设置为 FullRowSelect。
我将 MultiSelect 设置为 True。
我希望能够 select 多行,然后检查第一列。这将选中或取消选中当前 selected 的所有复选框;然而,当我这样做时,selection 被删除,只有我单击其复选框的行将被 selected.
换句话说,我不想在单击复选框单元格时删除 selection。
我不熟悉 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;
}
但是您认为单击一个复选框并选中多个值是否直观?也许使用带有 Button "CheckSelection" 的 contextMenu 更直观。想想看 ;)
确保将 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);
}
}
}
我有一个 DataGridView,第一列是 DataGridViewCheckBoxColumn。 我将 SelectionMode 设置为 FullRowSelect。 我将 MultiSelect 设置为 True。
我希望能够 select 多行,然后检查第一列。这将选中或取消选中当前 selected 的所有复选框;然而,当我这样做时,selection 被删除,只有我单击其复选框的行将被 selected.
换句话说,我不想在单击复选框单元格时删除 selection。
我不熟悉 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;
}
但是您认为单击一个复选框并选中多个值是否直观?也许使用带有 Button "CheckSelection" 的 contextMenu 更直观。想想看 ;)
确保将 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);
}
}
}