我在VB.NET的Windows窗体上有列表框,列表框包含从数据库填充的作业列表。 然后使用列表框中选择的值构建SQL语句,然后发送该语句以创建报告。 我的问题是,我希望列表框在选择一个特定项目时取消选择所有其他项目。基本上我的问题是,当我选择项目0(所有作业的列表)时,我希望取消选择所有其他项目,如果选择了任何其他项目,则必须取消选择项目0。 项目0 =基本上是一组工作。 剩余项目=个人工作。 以下是我用来加载列表框的代码
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
及以下是我可以设法在选择索引= 0的项目时取消选择所选项目的代码,这是答案的一半,但我也希望它以其他方式发生,我的意思是如果其他项目如选择其他然后在index = 0处的项目,则必须取消选择index = 0处的项目。
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
答案 0 :(得分:0)
您可以尝试这样的事情:
' If only 1 item is selected, then do nothing
If ListBox1.SelectedItems.Count > 1 Then
' If there is more than one item selected and
' one of those items is the first item
If ListBox1.SelectedIndex = 0 Then
' Clear all selected items
ListBox1.SelectedItems.Clear()
' Select only the first item
ListBox1.SetSelected(0, True)
End If
End If