Solved

How to select items from listbox and use sqlcommand

Posted on 2010-11-29
4
411 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
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
ASP.net See list of pdf documents in folder and read 2 28
Asp.net mvc entity issue 6 30
Cannot upload files above 1mb IIS7 11 39
Authentication of Web Services 3 46
In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
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.
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

932 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

13 Experts available now in Live!

Get 1:1 Help Now