Solved

How to select items from listbox and use sqlcommand

Posted on 2010-11-29
4
409 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:HainKurt
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video discusses moving either the default database or any database to a new volume.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now