Vb.net 在列表框中选择特定项目时取消选择项目
我在VB.NET的windows窗体上有一个列表框,该列表框包含从数据库填充的作业列表。 然后,在列表框上选择的值用于构建SQL语句,然后发送该语句以创建报告。 我的问题是,当选择一个特定项目时,我希望列表框取消选择所有其他项目。基本上,我的问题是,当我选择了所有作业列表中的项目0时,我希望所有其他项目都不被选中,如果选择了任何其他项目,则必须不选中项目0。 项目0=基本上是一组作业。 剩余项目=单个作业。 下面是我用来加载列表框的代码Vb.net 在列表框中选择特定项目时取消选择项目,vb.net,winforms,listbox,Vb.net,Winforms,Listbox,我在VB.NET的windows窗体上有一个列表框,该列表框包含从数据库填充的作业列表。 然后,在列表框上选择的值用于构建SQL语句,然后发送该语句以创建报告。 我的问题是,当选择一个特定项目时,我希望列表框取消选择所有其他项目。基本上,我的问题是,当我选择了所有作业列表中的项目0时,我希望所有其他项目都不被选中,如果选择了任何其他项目,则必须不选中项目0。 项目0=基本上是一组作业。 剩余项目=单个作业。 下面是我用来加载列表框的代码 Public Sub CommandCollection(
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的项目被选中时,我可以设法取消选中所选项目,这是答案的一半,但我也希望它以另一种方式发生,我的意思是,如果其他项目被选中,而索引=0的项目则必须取消选中索引=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
您可以尝试以下方法:
' 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
告诉我们你的代码和你被卡住的地方。我已经在我被卡住的地方添加了代码