在DataGridView CheckBox中限制检查

时间:2017-12-31 15:02:48

标签: c# checkbox datagridview

enter image description here我有DataGridView CheckBox,现在我的问题是如何设置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());
}

1 个答案:

答案 0 :(得分:1)

此示例允许复选框仅更改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;
        };
    }
}