Solved

How to select items from listbox and use sqlcommand

Posted on 2010-11-29
4
420 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 53

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

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…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

752 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