数据网格复选框列选择无法正常工作
我想要一个带有复选框的列,当用户单击它们时,他们会选择自己的行(突出显示它)。我已经想出了这段代码,但不能完成工作,我该如何修复它?
有更好的方法吗? (即使在我“取消选中”复选框后,该行仍保持突出显示)。
private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == true)
dataGrid.Rows[e.RowIndex].Selected = false;
else if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == false)
dataGrid.Rows[e.RowIndex].Selected = true;
}
}
I want to have a column with checkboxes that when ever the user clicks them, they select their own row (hightlight it). I have come up with this code, with does not do the job, how can I fix it?
Is there a better way of doing this? (The row stays highlighter even after I "uncheck" the checkbox).
private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == true)
dataGrid.Rows[e.RowIndex].Selected = false;
else if (Convert.ToBoolean(dataGrid.Rows[e.RowIndex].Cells[0].Value) == false)
dataGrid.Rows[e.RowIndex].Selected = true;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将逻辑放入
CellMouseUp
事件处理程序中,因为CellClick
事件在 CheckBox 状态更新之前发生。这与使用
EditedFormattedValue
属性(包含单元格的当前格式化值)来检索 CheckBoxes 当前状态。
来自 MSDN:
这是一个工作示例。
希望这有帮助。
Try placing the logic in a
CellMouseUp
event handler as theCellClick
event is occurring before the CheckBox state has been updated.This along with using the
EditedFormattedValue
property (which contains the current, formatted value of the cell) to retrieve the CheckBoxes current state.From MSDN:
Here is a working example.
Hope this helps.
CellMouseUp
不适用于按空格键进行选择。如果您不必进行“真实”选择,我会在单元格值更改时更改行背景颜色,这会更容易:
CellMouseUp
will not work for selection with SPACE press.If you don't have to do "real" selection, I'd change row background color on cell value change, it'd be much easier: