Solved

How to select items from listbox and use sqlcommand

Posted on 2010-11-29
4
416 Views
Last Modified: 2012-08-13
Hi,

I want to select * from table where xxx = listbox.items

I have tried this:
SelectCommand="SELECT * FROM [XXX] WHERE [XXX] IN (@listbox)">
                 
                 <SelectParameters>  
                    <asp:ControlParameter ControlID="listbox" Name="listbox" Type="String" />                  
                                       
                 </SelectParameters>

Open in new window

0
Comment
Question by:mattegol
4 Comments
 
LVL 51

Expert Comment

by:Huseyin KAHRAMAN
ID: 34230061
remove the select parameter and and write a code for listbox_change event and get all selected values put into a string like

if it is a number : "1, 2, 3"
if it is string : "'Hain', 'Kurt', 'EE'"

then change the select command like:

SelectCommand="SELECT * FROM [XXX] WHERE [XXX] IN (" & selected_values & ")"

then reQuery/re-bind/refresh the control to get the new values from db...
0
 
LVL 5

Expert Comment

by:logideepak
ID: 34230119
you would need to create a procedure and a function and pass the comma seperated values to the procedure which would ultimately return a table object and then you can

select * from table where xxx in (Select ufn_CommaseperatedToTable(comma sepearated values)


Let me know if you want another code snippet for the procedure as well to see how the whole thing would work,.
create FUNCTION [dbo].[ufn_CommaseperatedToTable] ( @StringInput VARCHAR(8000) )
RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN

    DECLARE @String    VARCHAR(10)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(',', @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(',', @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [String] )
        VALUES ( @String )
    END
    
    RETURN
END

Open in new window

0
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 250 total points
ID: 34230475
Here's a complete solution in C# with examples for using "All Items" and "Only Selected Items" in the ListBox.  If you want this to happen on a user triggered event, simply move the code from the Page_Load() event into your desired event handler.

//ASP Markup

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" >
            <asp:ListItem Text="Item1" />
            <asp:ListItem Text="Item2" />
        </asp:ListBox>
    </div>
    </form>
</body>
</html>



//Code Behind:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder items = new StringBuilder();
        bool first = true;

        //Using ALL items from ListBox:
        foreach (ListItem item in ListBox1.Items)
        {
            if (first) first = false;
            else items.Append(", ");
            items.Append("'" + item.Text + "'");
        }

        string sql = "SELECT * FROM [XXX] WHERE [XXX] IN (" + items.ToString() + ")";
        DataTable table = GetTable(sql);

        items = new StringBuilder();
        first = true;

        //Using only the selected items from ListBox:
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
            {
                if (first) first = false;
                else items.Append(", ");
                items.Append("'" + item.Text + "'");
            }
        }

        sql = "SELECT * FROM [XXX] WHERE [XXX] IN (" + items.ToString() + ")";
        DataTable table2 = GetTable(sql);
    }

    private DataTable GetTable(string sql)
    {
        DataTable table = new DataTable();
        SqlConnection conn = new SqlConnection("YourDbConnectionString");
        SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);

        try
        {
            adapter.Fill(table);
        }
        catch (Exception ex)
        {
            string error = ex.ToString();
        }
        finally
        {
            adapter.Dispose();
            conn.Dispose();
        }

        return table;
    }
}

Open in new window

0
 
LVL 3

Expert Comment

by:Sokrates
ID: 34230565
hmmm... it took me a while and i came into these findings:

You cannot have a Select Parameter and pass multiple values on to it. Even if it just a parameter, you are using a control parameter which is impossible to do it.

I found a solution for you.... Here it goes:

1)This will be your datasource which need to call the event SqlDataSource1_Selecting
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings %>" ProviderName="<%$ ConnectionStrings:ProviderName %>" SelectCommand="SELECT * FROM XXX" OnSelecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>

2)SqlDataSource1_Selecting event
string myitems = "";
//strings XXX is a string
for (int j = 0; j < listbox.Items.Count; j++) myitems += "'" + listbox.Items[j].Value + "',";
//numbers XXX is a number
//for (int j = 0; j < DropDownList1.Items.Count; j++) myitems += listbox.Items[j].Value + ",";
e.Command.CommandText += " WHERE (XXX IN (" + myitems.Substring(0, myitems.Length-1) + "))";
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question