I have listbox on a windows form in VB.NET, the list box contains list of jobs, which are populated from a database. The values selected on the listbox are then used to built up a SQL statement which is then sent to create a report. My problem is, I want the list box to deselect all other items when one particular item is selected. Basically my problem is, when I selected item 0 (which is list of all jobs)I want all other items to be unselected and if any other items are selected, Item 0 must be unselected. Item 0 = is basically and group of jobs. remaining Items = individual jobs. Below is the code which i'm using to load listbox
Public Sub CommandCollection()
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
ListBox1.Enabled = False
BtnClosedJobActualQuoteViewer_Click.Enabled = True
Dim sql As String = Nothing
connetionString = "Data Source=DEV-TST235\SQLEXPRESS2005;Initial Catalog=TSTracker;Integrated Security=True"
sql = "SELECT -1 JobId, '<All>' JobNumber" & _
" UNION " & _
" SELECT * from (SELECT DISTINCT Jobs.JobId,RTRIM(Jobs.JobNumber) JobNumber FROM Jobs INNER JOIN" & _
" Companies (NOLOCK) ON Jobs.CustomerID = Companies.CompanyID INNER JOIN" & _
" JobHistory (NOLOCK) ON Jobs.JobID = JobHistory.JobID" & _
" WHERE (JobHistory.modifiedDate > '" & StartDate.Value.ToShortDateString & "') AND (JobHistory.modifiedDate < '" & EndDate.Value.ToShortDateString & "') AND (JobHistory.Description = 'Job Closed')" & _
")a ORDER BY JobNumber"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ListBox1.DataSource = ds.Tables(0)
ListBox1.ValueMember = "JobId"
ListBox1.DisplayMember = "JobNumber"
ListBox1.ClearSelected()
If ListBox1.Items.Count > 1 Then
ListBox1.Enabled = True
Else
ListBox1.Enabled = False
ListBox1.DataSource = Nothing
ListBox1.Items.Clear()
BtnClosedJobActualQuoteViewer_Click.Enabled = False
End If
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
End Sub
and below is the code where i can manage to unselect the selected items when an item at index=0 is selected which is half of the answer but i also want it to happen in the other way, i mean if other items as selected other then the item at index = 0 then the item at index= 0 must be unselected.
Dim index As Integer
index = ListBox1.SelectedIndex
If index = 0 Then
ListBox1.SelectedItems.Clear()
ListBox1.SetSelected(0, True)
ElseIf index <> 0 Then
ListBox1.SetSelected(0, False)
End If
End If