Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 424
  • Last Modified:

How to select items from listbox and use sqlcommand

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
mattegol
Asked:
mattegol
1 Solution
 
HainKurtSr. System AnalystCommented:
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
 
logideepakCommented:
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
 
P1ST0LPETECommented:
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
 
SokratesCommented:
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now