我有一个包含2个列表框的表单。这里,listbox1填充了演员和女演员的名字。如果从listbox1中选择了一个名称,则listbox2应该显示涉及该名称的电影的标题。如果选择了其他名称,listbox2将显示涉及2名称的电影的标题。
Call Connect()
With Me
STRSQL = "select mTitle from selectmovie where cName = '" & lstNames.SelectedItem & "'"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = myCmd
myAdptr.Fill(myDataTable)
lstTitle.DisplayMember = "mTitle"
lstTitle.ValueMember = "mTitle"
If myDataTable.Rows.Count > 0 Then
For i As Integer = 0 To myDataTable.Rows.Count - 1
lstTitle.Items.Add(myDataTable.Rows(i)("mTitle"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
没有错误。当我选择1项时,结果是正确的,但它留下了很多空间......我的表格的屏幕截图:http://www.flickr.com/photos/92925726@N06/8445945758/in/photostream/
当我选择了actor3:http://www.flickr.com/photos/92925726@N06/8445945724/in/photostream/
时,输出变得更糟答案 0 :(得分:1)
您的主要问题似乎是您在使用新选择重新加载之前未清除lstTitle
控件。因此,每次选择新名称时,它都会将该名称的所有标题添加到已加载的现有标题列表中。此外,不是使用整数来迭代所有索引,而是使用For Each
循环更容易:
lstTitle.Items.Clear()
For Each row As DataRow In myDataTable.Rows
lstTitle.Items.Add(row("mTitle"))
Next
但是,我还必须提到你真的应该在查询中使用一个参数,而不是像这样动态构建SQL语句,例如:
myCmd.CommandText = "select mTitle from selectmovie where cName = @name"
myCmd.Parameters.AddWithValue("name", lstNames.SelectedItem)
要选择涉及所有多个选定actor的所有电影,您需要为每个actor的where子句添加一个附加条件,例如:
Dim builder As New StringBuilder()
builder.Append("select distinct mTitle from selectmovie where ")
For i As Integer = 0 to lstNames.SelectedItems.Count - 1
Dim parameterName As String = "@name" & i.ToString()
If i <> 0 Then
builder.Append("and ")
End If
builder.Append(parameterName)
builder.Append(" in (select cName from selectmovie where mTitle = m.mTitle) ")
myCmd.Parameters.AddWithValue(parameterName, lstNames.SelectedItems(i))
Next
myCmd.CommandText = builder.ToString()