How can visible a button only when a check box of a Data Grid View is checked????

Recommended Answers

All 2 Replies

Loop through the rows of DGV, and check is there is at least one checkBox checked. If there is, Enable the button, if not, leave it Disabled (this is in case if you will check on some button click event, and not when checking ot unchecking a comboBox)

If you wanna check the actual state of current checkBox, you will have to use two events of DGV:
1. CurrentCellDirtyStateChanged
2. CellValueChanged

What i mean is, if you add (or remove) a tick into a checkBoxCell, these two events will fire, and then you can check the actual state of current checkBoxCell value.

I suggest you to create a class integer variable, which will count the number of checkBoxes checked. Then you do the checking in the CellValueChanged, if the value is 0 Disable a button, if the value is greater then zero, enable it.

Here is the example code:

//class variable (put it on the top of the code!
        int checkBoxCounter;

        void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dataGridView1.IsCurrentCellDirty)
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void dataGridView1_CellValueChanged(object obj, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1) //compare to checkBox column index
            {
                DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];
                if (checkCell =! null)
                {
                     if((bool)checkCell.Value == true)
                         checkBoxCounter++;  //count + 1;
                     else
                         checkBoxCounter--;   //subtract 1 (-1)
                }
            }

            //here you can do the checking or button will be enabled or disabled:
            if(checkBoxCounter > 0)
                button1.Enabled = true;
            else if(checkBoxCounter == 0)
                button1.Enabled = false;                
        }

This is it. And do not forget to create these two events, not just pasting it into your code!

Ok let see. thanks for the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.