在DataGridView CheckBox中限制检查

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在DataGridView CheckBox中限制检查相关的知识,希望对你有一定的参考价值。

enter image description here我有一个DataGridViewCheckBox,现在我的问题是我如何设置限制CheckBox可以checked多少说3?我已经有了计算检查CheckBox的数量的代码。我是编程新手,对不起我的英语不好。

private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
        bool isChecked = Convert.ToBoolean(DataGridView1.Rows[DataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString());

        if (isChecked)
        {
            num += 1;
        }
        else
        {
            num -= 1;
        }
        MessageBox.Show(num.ToString());
}
答案

此示例允许复选框仅更改3次。在进入editmode之前,检查复选框是否已更改3次。如果是,则将取消编辑模式。在每个提交的编辑中,计数器将在单元格的Tag属性中更新。

dataGridView1.CellBeginEdit += ( sender , e ) =>
{
    var dataGridViewCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    if ( dataGridViewCell.ValueType == typeof(bool))
    {
        var checkedCount = dataGridViewCell.Tag is int ? ( int )dataGridViewCell.Tag : 0;
        e.Cancel = checkedCount == 3;
    }                
};
dataGridView1.CellEndEdit += ( sender , e ) =>
{
    var dataGridViewCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
    if ( dataGridViewCell.ValueType == typeof(bool))
    {
        var checkedCount = dataGridViewCell.Tag is int ? ( int )dataGridViewCell.Tag : 0;
        dataGridViewCell.Tag = checkedCount + 1;
    }
};

此示例仅允许网格中的3个已选中复选框:

public partial class Form1 : Form
{
    private int _checkedCount;

    public Form1()
    {
        InitializeComponent();

        dataGridView1.CellBeginEdit += ( sender , e ) =>
        {
            var dataGridViewCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            if ( dataGridViewCell.ValueType == typeof( bool ) )
                e.Cancel = _checkedCount == 3;
        };

        dataGridView1.CellValueChanged += ( sender , e ) =>
        {
            var dataGridViewCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
            if ( dataGridViewCell.ValueType == typeof( bool ) )
                _checkedCount += 1;
        };
    }
}

以上是关于在DataGridView CheckBox中限制检查的主要内容,如果未能解决你的问题,请参考以下文章

DataGridView

DataGridView 动态绑定 CheckBox

如何检测 DataGridView CheckBox 事件变化?

WinForm中datagridview里怎样判断checkbox是不是被选中~

winform中datagridview中的checkbox选中问题

在datagridview中如何使用checkbox作为radiobutton?