Reputation: 13
I have DataGridView1 that contain n number of column i want user to select the column that he want to save then i save it ..(done)
The problem here that i want the user to select only 3 column and on four column give user massage that he/she have to select only three.
To unselect the last one i use DataGridView1_ColumnHeaderMouseClick
Event and I present the message but can not find anything like DataGridView1.SelectColumn = False
If DataGridView1.SelectedColumns.Count > 3 Then
MsgBox("You have to choose 3 columns only")
Exit Sub
End If
Upvotes: 0
Views: 1412
Reputation: 3207
I'm not convinced you can count the selected columns that way. Anyway, here's a way to use the args of the event to achieve what I think you're trying to achieve:
Private Sub DataGridView1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
If DataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected) > 3 Then
MsgBox("You cannot select more than 3 columns.")
DirectCast(sender, System.Windows.Forms.DataGridView).Columns(e.ColumnIndex).Selected = False
End If
End Sub
I used a DirectCast
to get the sender to behave as the datagridview (which it is) because this way I could attach this event to several different dtagridviews, but if you dislike that form you can always use DataGridView1.Columns(e.ColumnIndex).Selected = False
instead.
Also, I use the e.ColumnIndex
to unselect the last column the user clicked on because I though that it was what you were trying to do, but you can change this comportment for something more suitable to your needs as you now know how to unselect columns.
Have fun!
Upvotes: 1