【发布时间】:2010-03-09 21:55:14
【问题描述】:
我想将 ListBox 中的多个选定值作为参数传递给我的 Select SQL 查询。
我正在使用 VB.NET,我该如何实现?...
【问题讨论】:
标签: sql select listbox selected
我想将 ListBox 中的多个选定值作为参数传递给我的 Select SQL 查询。
我正在使用 VB.NET,我该如何实现?...
【问题讨论】:
标签: sql select listbox selected
可能最好的开始方式是遍历列表框并仅获取被选中的项目。假设您使用的是 Web 表单,下面是一个示例:
For Each myItem As ListItem In myListBox.Items
If myItem.Selected Then
'Add the item to the list of parameters
End If
Next
【讨论】:
通过遍历列表框项目来选择您的项目,并将它们添加到某种集合中并传递它们。
For i = 0 To ListBox1.Items.Count - 1
If ListBox1.Items(i).Selected Then
' Add to collection
End If
Next
在这种情况下,将 SQL 语句包装在存储过程中可能是一个好主意,因为它可以让您灵活地发送参数。
我看到的另一个技巧是,当人们根据选择有不同数量的参数时,将选择附加到始终为真的条件,例如:
Base SQL = Select * From MyTable where 1=1
然后根据列表项(集合),可以选择性地“添加”Ands
【讨论】:
将选择模式设置为 SelectionMode.MultiExtended 或 SelectionMode.MultiSimple。 使用 SelectedItems 属性。
更新
我不知道你的 select 语句是什么,所以在 C# 中(抱歉没有 VB)
string sql = "select [columns] from [table] where [column] in (";
string delimiter = ",";
foreach(var selected in lb1.SelectedItems)
{
sql = String.Concat(sql, selected.text, delimiter);
}
sql = sql.Substring(0, sql.Length-1);
sql = String.Concat(sql, @");");
【讨论】: