Click here to Skip to main content
15,894,720 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
M tried for this as below, but might be its wrong. Please suggect me answer
C#
int count = 0;
            DataGridViewCheckBoxCell cell = new DataGridViewCheckBoxCell();
            cell = (DataGridViewCheckBoxCell)dgvTanksandCompartments.Rows[dgvTanksandCompartments.CurrentRow.Index].Cells[0];
           
           
           CheckBox box = (CheckBox)sender;           
            if (box.Checked)
            {
                count++;
            }

            if (count > 4)
            {
                MessageBox.Show("Error");
            }



I Want to check only 5 checkbox. If user select more than that, then give error.
Posted
Updated 31-Jul-14 1:12am
v2
Comments
arvind mepani 31-Jul-14 9:57am    
you have to iterate through all datagridview and check for all checkbox value then increment count for checked value.

1 solution

You could keep a running total of the number of checkboxes that are checked on your control.

A useful property for storing that information is the Tag which will hold any object. As integers are objects in .NET then it will do nicely.

Here's one way of doing it
C#
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0 && ((DataGridView)sender).IsCurrentRowDirty)
    {
        int count = (this.dataGridView1.Tag != null) ? (int)this.dataGridView1.Tag : 0;

        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)((DataGridView)sender).Rows[e.RowIndex].Cells[0];
        bool cb = (bool)cell.EditedFormattedValue; //NB NOT .Value

        if (cb)
            count++;
        else
            count--;

        if (count > 5)
        {
            MessageBox.Show("You can only tick 5 items");
            ((DataGridView)sender).CancelEdit();
        }
        else
            this.dataGridView1.Tag = count;
    }
}

Points to note
-: The CellContentClick event can be fired when the DGV is being populated, which is why I check for IsCurrentRowDirty
-: cell.Value doesn't return the value that you are moving the checkbox to, despite the fact you can "see" that it has been ticked. So use EditedFormattedValue instead
-: If you don't use .CancelEdit() then the checkbox remains ticked!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900