我想要一个WinForms DataGridView(datasource = DataTable),用户可以在其中选择多个复选框单元格并按空格键启用/禁用它们。只要不应用过滤器,这就可以正常工作。一旦我这样做,行索引为-1,我无法通过按空格键来选择所选单元格。
这是我用来通过按空格键来选择多个单元格的代码。
private void grdChannels_KeyUp(object sender, KeyEventArgs e)
{
string currentRowFilter = (grdChannels.DataSource as DataTable).DefaultView.RowFilter;
if (e.KeyCode == Keys.Space)
{
e.Handled = true;
DataGridViewSelectedCellCollection selectedCells = grdChannels.SelectedCells;
for (int i = 0; i < selectedCells.Count; i++)
{
if (selectedCells[i].RowIndex == -1)
continue; // Why do we get here if a RowFilter was added?
DataGridViewCell selectedCell = selectedCells[i];
if (!(selectedCell is DataGridViewCheckBoxCell))
continue;
DataGridViewCheckBoxCell selectedCheckBoxCell = (DataGridViewCheckBoxCell)selectedCell;
string cellVal = selectedCheckBoxCell.Value?.ToString();
bool currentCellVal = bool.Parse(string.IsNullOrEmpty(cellVal) ? "False" : cellVal);
selectedCheckBoxCell.Value = !currentCellVal;
}
grdChannels.BindingContext[grdChannels.DataSource].EndCurrentEdit();
}
}
这是我在数据网格上设置/重置过滤器的代码(grdChannels):
if (grdChannels.Columns[node.Key] != null)
(grdChannels.DataSource as DataTable).DefaultView.RowFilter = string.Format("[{0}] = true", node.Key.Trim());
else
(grdChannels.DataSource as DataTable).DefaultView.RowFilter = null;
我还必须添加此代码,以便在更改我的datagridview时更新它:
private void grdChannels_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// this is needed as cell values won't be commited as long as user doesn't change row or hits enter
grdChannels.BindingContext[grdChannels.DataSource].EndCurrentEdit();
}
private void grdChannels_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
grdChannels.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
一旦用户点击过滤视图中的复选框,该行就会获得一个索引,一切都按预期工作。但如果用户首先使用空格键,则索引始终为-1。我该如何解决这个问题?