private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Whatever index is your checkbox column
var columnIndex = 0;
if (e.ColumnIndex == columnIndex)
{
// If the user checked this box, then uncheck all the other rows
var isChecked = (bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (isChecked)
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Index != e.RowIndex)
{
row.Cells[columnIndex].Value = !isChecked;
}
}
}
}
}
Private Sub dataGridView_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DG_SubSyncs.CellValueChanged
Dim columnIndex As Integer = 0
If (e.ColumnIndex = columnIndex) Then
'If the user checked this box, then uncheck all the other rows
Dim isChecked As Boolean = CBool(DG_SubSyncs.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
If (isChecked) Then
For Each row In DG_SubSyncs.Rows
If (row.Index <> e.RowIndex) Then
row.Cells(columnIndex).Value = Not isChecked
End If
Next
End If
End If
End Sub
private void dataGridView_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
/// <summary>
/// This will be fired by CellContentClick event from above
/// </summary>
private void dataGridView_CellValueChanged(object sender,
DataGridViewCellEventArgs e)
{
//0 is checkbox column index
var columnIndex = 0;
if (e.ColumnIndex == columnIndex )
{
var isChecked = (bool)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (isChecked)
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Index != e.RowIndex)
{
row.Cells[columnIndex].Value = !isChecked;
}
}
}
}
}
//Bind the events in the form designer
this.dataGridView.CellContentClick += new DataGridViewCellEventHandler(this.dataGridView_CellContentClick);
this.dataGridView.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView_CellValueChanged);
8条答案
按热度按时间bnl4lu3b1#
k4ymrczo2#
订阅
CellContentClick
并添加dataGridView.EndEdit()
以获得更好的用户体验(单元格不必失去焦点才能触发事件):ff29svar3#
VB网络版
n1bvdmb64#
这里是一个稍微清理过的版本。我的复选框列是动态添加的,并且总是网格中的最后一列,但您可以理解:
0s0u357o5#
zaqlnxep6#
下面是我基于数据操作的答案。您需要表单中一个名为DataGridView1的数据网格视图,除此之外什么都不需要。
zaqlnxep7#
要处理
dataGridView_CellValueChanged
事件,我们必须触发dataGridView_CellContentClick
事件(它没有复选框的当前状态),将调用CommitEdit
。这将触发dataGridView_CellValueChanged
事件,我们可以在其中编写逻辑来选中/取消选中复选框。6mzjoqzu8#
您必须在DGV上将VirtualMode设置为TRUE才能只允许一个复选框。