I have a checkbox column in my datagrid view, and I want to restrict the user into checking 7 boxes only, no more, no less. Also, I want something to happen on every checkbox click. Like this (pseudo-code only):
While counter is not equal to 7 {
Check if the user clicked a checkbox (say, some random checkbox 1) {
(when I say random, I mean not in order, or in no particular order)
copy row data from where the user clicked the checkbox onto another form (data 1)
increment counter to 1
display msgbox saying that the user clicked '1 out of 7'}
Check if the user clicked another random checkbox (2) {
copy row data from where the user clicked the checkbox onto another form (data 2)
increment counter to 2
display msgbox saying that the user clicked '2 out of 7'}
.
.
.
Check if the user clicked another random checkbox (7) {
copy row data from where the user clicked the checkbox onto another form (data 7)
increment counter to 7
display msgbox saying that the user clicked '7 out of 7'}
If counter is more than 7, exit sub and display msgbox('You can only select 7 names')
I have tried several layers and different arrangements of FOR_NEXT loops to get this to work but I just can't make it work! Here is my code:
Private Sub dgvPaidComms_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvPaidComms.CellContentClick
Dim counter As Integer = 0
For Each row As DataGridViewRow In dgvPaidComms.Rows
Dim selected As Boolean = DataGridView1.Rows(e.RowIndex).Cells(0).Value
If selected = True Then
counter += 1
End If
Next
If counter > 7 Then
MsgBox("You can only select 7 names.")
Exit Sub
End If
End Sub
But what it does is loop through ALL of the rows in my DGV (which has 50+ rows) so it displays the MsgBox("You can only select 7 names.")
.
I have also tried using a normal FOR-NEXT loop (I mean, the normal counter thing. Like For counter As Integer = 0 to 7 ... Next
thing.) and putting the For Each row As DataGridViewRow In dgvPaidComms.Rows...
inside of it, and vice versa, only to get disappointed.
I am lost. I am really confused. I think it has something to do with the DataGridView1.Rows(e.RowIndex).Cells(0).Value
because I think it only captures one CellClick event (I mean, one checked checkbox. Because what happens when I try to run the code is, I check one checkbox, and I get MsgBox("You can only select 7 names.")
popping out because it really runs through all of the rows, and when I use the normal FOR_NEXT (explained above), It becomes an infinite loop.)
Can someone help me clear up this confusion?