views:

2088

answers:

1

I have a checkbox column in a DataGridView and I want to validate whether the user can check a checkbox by counting the number of checkboxes they click and deciding then to disable checking.

Can someone guide me how to do this effectively??

A: 

Quick code sample:

public partial class DGVCheckBoxTesting : Form
{

    private const int MAX_CHECKS = 5;

    public DGVCheckBoxTesting()
    {
        InitializeComponent();
        this.dataGridView1.Columns.Add("IntColumn", "IntColumn");
        this.dataGridView1.Columns.Add(new DataGridViewCheckBoxColumn { Name = "BoolColumn" });
        for (int i = 0; i <= 10; i++)
        {
            this.dataGridView1.Rows.Add(i, false);
        }

        this.dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
        this.dataGridView1.CellContentDoubleClick += new DataGridViewCellEventHandler(dataGridView1_CellContentDoubleClick);
    }

    private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        this.ValidateCheckBoxState(e);
    }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        this.ValidateCheckBoxState(e);
    }

    private void ValidateCheckBoxState(DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex != 1) //bool column
        { return; }

        this.dataGridView1.EndEdit();
        bool value = (bool)this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        int counter = 0;
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            if (row.Cells[1].Value != null && (bool)row.Cells[1].Value)
            {
                counter++;
            }
        }

        if (counter > MAX_CHECKS)
        {
            this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
            this.dataGridView1.EndEdit();
        }
    }


}

Basically, what this code does is it adds an Integer column and a Bool column to the DataGridView. Then, on the CellContentClick event, if the checkbox column was clicked, first we commit the edit (if you don't do this, you'll have all kinds of trouble figuring out if the checkbox is checked or not). Then, we loop through the rows and count all the checked rows. Then, if the amount is greater than what we want to allow, we just set it back to false, and again re commit the edit. Test it out, it works. May not be the most elegant solution, but the DGV can be tricky with the checkboxes, so this is how I would do it.

EDIT: Just a small edit, I hooked into the ContentDoubleClick event as well, as I noticed you were able to beat the validation if you quickly clicked on the cell. Should work better now.

BFree
Thanks BFree I will try it
Malcolm