removing item from comboBox if it matches a cetain cell in dataGridView in VB.net - vb.net

I have a list of names (employees) in a comboBox that I use to add into a dataGridView. I'm trying to make it so that once the employee is in the database and displayed in the dataGrid, their name is removed from the comboBox so as not to appear available to add to the dataGrid.
The code I've written for the task looks like it should work, but it doesn't.
Public Class Main
Public techPhones As New PhonesDataSet.TechCompanyPhonesDataTable
Public techPhonesTableAdapter As New PhonesDataSetTableAdapters.TechCompanyPhonesTableAdapter
Public employees As New PhonesDataSet.EmployeesDataTable
Public empTableAdapter As New PhonesDataSetTableAdapters.EmployeesTableAdapter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, MyBase.Activated
LoadForm()
End Sub
Private Sub cboEmployee_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboEmployee.SelectedIndexChanged
lblOffice.Text = "Office: " + cboEmployee.SelectedItem("Office")
lblPhone.Text = cboEmployee.SelectedItem("Phone")
lblEmpID.Text = cboEmployee.SelectedItem("EmpID")
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click, DataGridView1.CellDoubleClick
Dim addEmp As New AddEmployee(cboEmployee.SelectedItem("Employee"), cboEmployee.SelectedItem("Office"), cboEmployee.SelectedItem("Phone"), _
cboEmployee.SelectedItem("OfficeID"), cboEmployee.SelectedItem("EmpID"), cboEmployee.SelectedItem("Contract"), cboEmployee.SelectedItem("Returned"), _
cboEmployee.SelectedItem("Loaner"))
addEmp.ShowDialog()
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim name As String = DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(2).Value
Dim employee As String
For index As Integer = 0 To cboEmployee.Items.Count - 1 Step 1
If cboEmployee.Items(index)("Employee") = name Then
employee = cboEmployee.Items(index)("Employee")
cboEmployee.SelectedIndex = index
End If
Next
End Sub
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
techPhonesTableAdapter.DeleteQuery((DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1).Value))
LoadForm()
End Sub
Private Sub LoadForm()
techPhones = techPhonesTableAdapter.GetData()
DataGridView1.DataSource = techPhones
employees = empTableAdapter.GetData()
cboEmployee.DataSource = employees
cboEmployee.DisplayMember = ("Employee")
cboEmployee.ValueMember = ("EmpID")
lblOffice.Text = "Office: " + cboEmployee.SelectedItem("Office")
lblPhone.Text = cboEmployee.SelectedItem("Phone")
lblEmpID.Text = cboEmployee.SelectedItem("EmpID")
cboEmployee.Focus()
cboEmployee.SelectAll()
lblRowCount.Text = "There are " + DataGridView1.RowCount.ToString + " phones accounted for."
' the code below is supposed to check every row in the data grid against the employee list in
' cboEmployees and remove it from the list when they match
With DataGridView1
For indexDGV As Integer = 0 To .Rows.Count - 1 Step 1
cboEmployee.Items.Remove(.Rows(indexDGV).Cells(2).Value)
Next
End With
cboEmployee.Refresh()
End Sub
End Class
I've also tried this minor variation:
With DataGridView1
For indexDGV As Integer = 0 To .Rows.Count - 1 Step 1
For indexCBO As Integer = cboEmployee.Items.Count - 1 To 0 Step -1
If .Rows(indexDGV).Cells(2).Value = cboEmployee.Items(indexCBO)("Employee") Then
cboEmployee.Items.RemoveAt(indexCBO)
End If
Next
Next
End With

You don't even need to iterate through the comboBox items. .Remove (string) will work, and if the item you want to remove is not there, it ignores the command.
With DataGridView1
For indexDGV As Integer = 0 To .Rows.Count - 1 Step 1
cboEmployee.Items.Remove(.Rows(indexDGV).Cells(2).Value)
Next
End With

Try like this
With DataGridView1
For indexDGV As Integer = 0 To .Rows.Count - 1 Step 1
For indexCBO As Integer = cboEmployee.Items.Count - 1 To 0 Step -1
If .Rows(indexDGV).Cells(2).Value.Equals(cboEmployee.Items(indexCBO).Tostring()) Then
cboEmployee.Items.RemoveAt(indexCBO)
Exit For
End If
Next
Next
End With

Related

Visual basic 2010, database – how to fill specific field

I'm creating database connection in Visual Basic. When user click on "borrow book" it transfer chosen data into table used for lent books. It all works alright, but I need last thing. In my database in lent table I have attribute "End date of lent" and I want fill it everytime when user borrow a book with date today + 1 month (for instance, if now is 19/04/2016, end date will be 19/05/2016). I created method "BorrowTime" for this, but I don't know what I should type into and how can I get value of inserted row into "row". And sorry for horrible look of code and form...
Public Class frm_UserView
Dim BooksSource As New BindingSource
Dim BorrowSource As New BindingSource
Dim BooksView As New DataView
Dim BorrowView As New DataView
Dim ds As New DataSet
Dim Borrow As Byte
Private Sub frm_UserView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmr_Timer.Start()
Me.LoanerBooksTableAdapter.Fill(Me.GMITLibraryDataSet1.LoanerBooks)
Me.BooksTableAdapter.Fill(Me.GMITLibraryDataSet.Books)
BooksSource = dgd_UserBookView.DataSource
BooksView = CType(BooksSource.List, DataView)
ds = BooksView.DataViewManager.DataSet.Clone
BorrowSource.DataSource = ds
BorrowSource.DataMember = "Books"
BorrowView = CType(BorrowSource.List, DataView)
dgd_User_Borrow_View.DataSource = BorrowSource
End Sub
Private Sub btn_Borrow_Click(sender As System.Object, e As System.EventArgs) Handles btn_BorrowBook.Click
Borrow = 1
MoveBooks(dgd_UserBookView, BorrowView, Borrow)
dgd_User_Borrow_View.Sort(dgd_User_Borrow_View.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BorrowSource.MoveLast()
BorrowSource.MoveLast()
End Sub
Private Sub MoveBooks(ByRef source As DataGridView, ByRef target As DataView, ByRef borrow As Byte)
For i = 0 To source.SelectedRows.Count - 1
Dim numberOfRow As Integer
Dim row As DataRowView
row = target.AddNew()
Dim col As Int16 = 0
For Each cell As DataGridViewCell In source.SelectedRows(i).Cells
row.Item(col) = cell.Value
If borrow = 1 Then
numberOfRow = 0
BorrowTime(numberOfRow, dgd_User_Borrow_View)
End If
col = col + 1
Next
Next
Dim count As Int16 = source.SelectedRows.Count
For i = 0 To count - 1
source.Rows.RemoveAt(source.SelectedRows(0).Index)
Next
End Sub
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
Private Sub btn_ReturnBook_Click(sender As System.Object, e As System.EventArgs) Handles btn_ReturnBook.Click
Borrow = 0
MoveBooks(dgd_User_Borrow_View, BooksView, Borrow)
dgd_UserBookView.Sort(dgd_UserBookView.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BooksSource.MoveLast()
BooksSource.MoveLast()
End Sub
Private Sub btn_UserLogOut_Click(sender As System.Object, e As System.EventArgs) Handles btn_UserLogOut.Click
frm_Login.Show()
Me.Hide()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_Timer.Tick
Dim countBooks As Integer
Dim countLent As Integer
countBooks = BooksSource.Count
countLent = BorrowSource.Count
lbl_BookCounter.Text = "There are " + countBooks.ToString + " books"
lbl_BorrowCounter.Text = "You have lent " + countLent.ToString + " books"
End Sub
End Class
I need to put code here:
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
My form
Public Class frm_UserView
Dim BooksSource As New BindingSource
Dim BorrowSource As New BindingSource
Dim BooksView As New DataView
Dim BorrowView As New DataView
Dim ds As New DataSet
Dim Borrow As Byte
Private Sub frm_UserView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmr_Timer.Start()
Me.LoanerBooksTableAdapter.Fill(Me.GMITLibraryDataSet1.LoanerBooks)
Me.BooksTableAdapter.Fill(Me.GMITLibraryDataSet.Books)
BooksSource = dgd_UserBookView.DataSource
BooksView = CType(BooksSource.List, DataView)
ds = BooksView.DataViewManager.DataSet.Clone
BorrowSource.DataSource = ds
BorrowSource.DataMember = "Books"
BorrowView = CType(BorrowSource.List, DataView)
dgd_User_Borrow_View.DataSource = BorrowSource
End Sub
Private Sub btn_Borrow_Click(sender As System.Object, e As System.EventArgs) Handles btn_BorrowBook.Click
Borrow = 1
MoveBooks(dgd_UserBookView, BorrowView, Borrow)
dgd_User_Borrow_View.Sort(dgd_User_Borrow_View.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BorrowSource.MoveLast()
BorrowSource.MoveLast()
End Sub
Private Sub MoveBooks(ByRef source As DataGridView, ByRef target As DataView, ByRef borrow As Byte)
For i = 0 To source.SelectedRows.Count - 1
Dim numberOfRow As Integer
Dim row As DataRowView
row = target.AddNew()
Dim col As Int16 = 0
For Each cell As DataGridViewCell In source.SelectedRows(i).Cells
row.Item(col) = cell.Value
If borrow = 1 Then
numberOfRow = 0
BorrowTime(numberOfRow, dgd_User_Borrow_View)
End If
col = col + 1
Next
Next
Dim count As Int16 = source.SelectedRows.Count
For i = 0 To count - 1
source.Rows.RemoveAt(source.SelectedRows(0).Index)
Next
End Sub
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
Private Sub btn_ReturnBook_Click(sender As System.Object, e As System.EventArgs) Handles btn_ReturnBook.Click
Borrow = 0
MoveBooks(dgd_User_Borrow_View, BooksView, Borrow)
dgd_UserBookView.Sort(dgd_UserBookView.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BooksSource.MoveLast()
BooksSource.MoveLast()
End Sub
Private Sub btn_UserLogOut_Click(sender As System.Object, e As System.EventArgs) Handles btn_UserLogOut.Click
frm_Login.Show()
Me.Hide()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_Timer.Tick
Dim countBooks As Integer
Dim countLent As Integer
countBooks = BooksSource.Count
countLent = BorrowSource.Count
lbl_BookCounter.Text = "There are " + countBooks.ToString + " books"
lbl_BorrowCounter.Text = "You have lent " + countLent.ToString + " books"
End Sub
End Class

How i can retrive the data from datagridview row click to corresponding data to another form

i am trying to retrieve data from one form to another form , on gridview click event. I have small code I got it from google search but its giving me error. in this code I was trying to retrieve it to second form datagrid. please check my code. where I am wrong.
Private Sub ReceiveGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For j As Integer = 0 To frmGoodsReceive.dgvPODetails.RowCount - 1
If frmGoodsReceive.dgvPODetails.Rows(j).Cells(0).Value = True Then
Dim count As Integer = 0
For i As Integer = 0 To frmGoodsReceive.dgvPODetails.ColumnCount - 1
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value
Next
count += count
End If
Next
End Sub
I am getting this error, while I run.
Conversion from string "PO003" to type 'Boolean' is not valid.
please help me
what I have the code that totally wrong code I guess. because what I am trying to do is , I have one gridview, and some data on that, when I click the row on datagrid , I want to open the corresponding information to second form gridview. this is the right way to do that?
Try Adding...
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value.ToString
Ohhh okay i get it remove the if statement to transfer all your data into the form:
Private Sub ReceiveGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For j As Integer = 0 To frmGoodsReceive.dgvPODetails.RowCount - 1
Dim count As Integer = 0
For i As Integer = 0 To frmGoodsReceive.dgvPODetails.ColumnCount - 1
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value
Next
count += count
Next
End Sub
Or replace the if condition if you want to get all data without NULL value or Nothing
Private Sub ReceiveGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For j As Integer = 0 To frmGoodsReceive.dgvPODetails.RowCount - 1
If frmGoodsReceive.dgvPODetails.Rows(j).Cells(0).Value.ToString <> "" Then
Dim count As Integer = 0
For i As Integer = 0 To frmGoodsReceive.dgvPODetails.ColumnCount - 1
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value
Next
count += count
End If
Next
End Sub
Check if both DataGridView Has The Same Column if not the error may Occur ex. if your passing 10 datas vs 20 datas on other datagridview, the first datagridview will be insufficient to give required data needed by the second datagridview.
Try to analyze this one...
Solution1: DataGridView1 > DataGridview 2
Use this Code
Private Sub ReceiveGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For j As Integer = 0 To frmGoodsReceive.dgvPODetails.RowCount - 1
Dim count As Integer = 0
For i As Integer = 0 To frmGoodsReceive.dgvPODetails.ColumnCount - 1
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value
Next
count += count
Next
End Sub
Solution2:DataGridview1 < DataGridview2
Use this Code
Private Sub ReceiveGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For j As Integer = 0 To Me.dgvReceiveGoods.RowCount -1
If frmGoodsReceive.dgvPODetails.Rows(j).Cells(0).Value.ToString <> "" Then
Dim count As Integer = 0
For i As Integer = 0 To frmGoodsReceive.dgvPODetails.ColumnCount - 1
Me.dgvReceiveGoods.Rows(count).Cells(i).Value = frmGoodsReceive.dgvPODetails.Rows(j).Cells(i).Value
Next
count += count
End If
Next
End Sub
Solution3:DataGridView1 = DataGridView 2
you can use Both...

Run Random event once?

The code below runs and keeps repeating over and over again. I only pasted the up_timer but others do the same. Any ideas on how to make it run once, then repeat to the random loop and so on?
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Application.DoEvents()
Randomize()
Dim value As Integer = CInt(Int((4 * Rnd()) + 1))
If value = 1 Then
MsgBox("Up")
up.Start()
ElseIf value = 2 Then
MsgBox("Down")
down.Start()
ElseIf value = 3 Then
MsgBox("Left")
left.Start()
ElseIf value = 4 Then
MsgBox("Right")
right.Start()
End If
Timer1.Stop()
End Sub
Private Sub up_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up.Tick
Static moveCount As Integer = 1
If Me.mob2.Location.Y > 12 Then
Me.mob2.Location = New Point(Me.mob2.Location.X, Me.mob2.Location.Y - 5)
End If
moveCount += 1
If moveCount = 10 Then
moveCount = 1
Me.Timer1.Start()
Me.up.Stop()
End If
End Sub
Looks like this is what you need, based on your complaint that timer1 repeats same numbers
Dim rand1 As New Random(CInt(Date.Now.Ticks And &h0000FFFF))
Dim value As Integer = rand1.Next(1, 4)
This will not repeat
Plus, you have to move Timer1.Stop() to beginning of the method

The button.BackColor statement seem to be executed, but no colour change is show

I'm trying to re-create the classic game "Simon" for a project. The code I have here should hopefully create a random number, translate that to a colour change for a random button, wait a short time, and then do the same for another random button. I can't spot any problems, but on execution the buttons remain uchanged.
Public Class MenuForm
Dim failure As Boolean
Dim pattern() As Integer
Dim maincounter As Integer = 1
Dim diff As Integer
Dim sender As Object
Dim e As EventArgs
Dim timewaited As Integer
Dim timefinished As Boolean
Private Sub Menuform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get the difficulty level from the player
Dim InputtedDifficulty As Integer = InputBox("Please enter difficulty. 1-Easy 2-Medium 3-Hard")
'Validate difficulty choice
Do While InputtedDifficulty > 3 Or InputtedDifficulty < 1
InputtedDifficulty = InputBox("Input incorrect. Please re-enter selection. 1-Easy 2-Medium 3-Hard")
Loop
'Set speed of blinking based on difficulty choice
Select Case InputtedDifficulty
Case 1
diff = 1000
Case 2
diff = 500
Case 3
diff = 20
End Select
End Sub
Private Sub run_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles run.Click
Call GameController()
End Sub
Private Sub GameController()
Dim buttonRepeater As Integer
'Call checkFail()
Do While failure = False
maincounter = maincounter + 1
Call Pattern_creator(sender, e)
For buttonRepeater = 1 To maincounter
Call button_controller(sender, e)
timewaited = 0
timefinished = False
ButtonTimer.Enabled = True
If timefinished = True Then
End If
Button1.BackColor = Color.Blue
Button2.BackColor = Color.Blue
Button3.BackColor = Color.Blue
Button4.BackColor = Color.Blue
Next buttonRepeater
Loop
End Sub
Private Sub Pattern_creator(ByVal sender As System.Object, ByVal e As System.EventArgs)
ReDim Preserve pattern(maincounter)
Randomize()
pattern(maincounter) = Int((Rnd() * 4) + 1)
ReDim Preserve pattern(maincounter + 1)
End Sub
Private Sub button_controller(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Ths case statement takes the random number generated earlier and translates that to
'a button flash
Select Case pattern(maincounter)
Case 1
Button1.BackColor = Color.Red
Case 2
Button2.BackColor = Color.Red
Case 3
Button3.BackColor = Color.Red
Case 4
Button4.BackColor = Color.Red
End Select
End Sub
Private Sub ButtonTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonTimer.Tick
If timewaited = 5 Then
ButtonTimer.Enabled = False
timefinished = True
Else
timewaited = timewaited + 1
End If
End Sub
End Class
Any help would be very much appreciated, I've been staring at this for ages with no progress.

How to Check or Uncheck all Items in VB.NET CheckedListBox Control

I need to select and unselect all items in a VB.NET CheckedListBox control, what is the best way to do this?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With clbCheckedListBox
.Items.Add("Select/UnSelect All")
.Items.Add("Enero")
.Items.Add("Febrero")
.Items.Add("Marzo")
.Items.Add("Abril")
.Items.Add("Mayo")
.Items.Add("Junio")
.Items.Add("Julio")
.Items.Add("Agosto")
.Items.Add("Septiembre")
.Items.Add("Octubre")
.Items.Add("Noviembre")
.Items.Add("Diciembre")
.SelectedIndex = 0
End With
End Sub
Private Sub clbCheckedListBox_ItemCheck(sender As Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
If e.NewValue = CheckState.Checked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Checked)
Next
ElseIf e.NewValue = CheckState.Unchecked Then
For idx As Integer = 1 To Me.clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, CheckState.Unchecked)
Next
End If
End If
End Sub
After Hours the above code work fine for me !
Do you mean something like this:
Dim checked As Boolean = True ' Set to True or False, as required.
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, checked)
Next
Here I'm just looping through all the CheckedListBox Items and setting their checked state.
Ricardo, perhaps this might be what you are looking for:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim items$() = New String() {"Select/UnSelect All", "Enero",
"Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}
For Each Str As String In items : clbCheckedListBox.Items.Add(Str) : Next
End Sub ' Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs)
Private Sub clbCheckedListBox_ItemCheck(sender As System.Object, e As System.Windows.Forms.ItemCheckEventArgs) Handles clbCheckedListBox.ItemCheck
If e.Index = 0 Then
Dim newCheckedState As CheckState = e.NewValue
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemCheckState(idx, newCheckedState)
Next
End If
End Sub
To check all CheckedListBox Item:
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
Next
To uncheck all CheckedListBox Item:
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, false)
Next
If button.Text = "Select All" Then
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, True)
Next
Button.Text = "Deselect All"
Else
For i As Integer = 0 To checklist.Items.Count - 1
checklist.SetItemChecked(i, False)
Button.Text = "Select All"
Next
End If
I found that clbCheckedListBox.clearSelection() works well for unselecting all.
Added a separate checkbox called "Select All". On checking and unchecking of this checkbox items of a checklistbox can be selected or unselected. So you can call this Kb() function anywhere in your code:
Private Sub ChkSelectAll_Click(sender As Object, e As EventArgs) Handles ChkSelectAll.Click
Kb(ChkSelectAll.CheckState)
End Sub
Private Sub Kb(ByVal Key As Boolean)
For i As Integer = 0 To ChkLstServices.Items.Count - 1
ChkLstServices.SetItemChecked(i, Key)
Next
End Sub
Put this code in the SelectedValueChanged event.
Private Sub clbCheckedListBox_SelectedValueChanged(sender As Object, e As System.EventArgs) Handles ContrListCheckBox.SelectedValueChanged
If clbCheckedListBox.SelectedIndex = 0 Then
If clbCheckedListBox.GetItemChecked(0) = False Then
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
Me.clbCheckedListBox.SetItemChecked(idx, False)
Next
Else
For idx As Integer = 1 To ContrListCheckBox.Items.Count - 1
Me.clbCheckedListBox.SetItemChecked(idx, True)
Next
End If
ElseIf clbCheckedListBox.SelectedIndex > 0 Then
If clbCheckedListBox.CheckedItems.Count = clbCheckedListBox.Items.Count - 1 And clbCheckedListBox.GetItemChecked(0) = False Then
clbCheckedListBox.SetItemCheckState(0, CheckState.Checked)
End If
For idx As Integer = 1 To clbCheckedListBox.Items.Count - 1
If clbCheckedListBox.GetItemChecked(idx) = False Then
clbCheckedListBox.SetItemCheckState(0, CheckState.Unchecked)
End If
Next
End If
End Sub
Other solutions are correct but if you want to deselect another checkbox inside the CheckBoxList or empty the CheckBoxList without the Select All checkbox
the top checkbox will remain checked and it is not logical so the above code should solve this problem.
Another option would be to bundle the check/uncheck events - of two buttons, for example - into one handler and use the value of sender to set the check state:
Private Sub clbCheckedListBox(
ByVal sender As Object,
ByVal e As EventArgs) Handles btnAll.Click, btnNone.Click
For i As Integer = 0 To clbApis.Items.Count - 1
clbApis.SetItemChecked(i, sender Is btnAll)
Next i
End Sub