ListBox的多个选定值作为SELECT SQL查询的参数

时间:2010-03-09 21:55:14

标签: sql select listbox selected

我想将ListBox中的多个选定值作为参数传递给我的Select SQL Query。

我正在使用VB.NET,我该如何实现?...

3 个答案:

答案 0 :(得分:0)

开始的最佳方式可能是遍历列表框并仅获取所选项目。假设您使用的是Web表单,以下是一个示例:

For Each myItem As ListItem In myListBox.Items
    If myItem.Selected Then
        'Add the item to the list of parameters
    End If
Next

答案 1 :(得分:0)

通过迭代列表框项目选择您的项目,并将它们添加到某种类型的集合中并传递它们。

For i = 0 To ListBox1.Items.Count - 1
   If ListBox1.Items(i).Selected Then
       ' Add to collection
   End If
Next

在这种情况下,将SQL语句包装在存储过程中可能是一个好主意,因为它会为您提供发送参数的灵活性。

我所看到的另一个技巧是,当人们根据选择有不同数量的参数时,会将选择附加到一个始终为真的条件,如:

基础SQL =选择*来自MyTable,其中1 = 1

然后根据列表项(集合),您可以选择性地“添加”Ands

答案 2 :(得分:0)

将选择模式设置为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, @");");