multi line select in list box in asp.net

I have an ASP.NET form in which I am using a listbox. I have set the selectionmode property to "Multiple". what i want to do is all the items that are selected from the listbox i want to pass it to a variable with comma as a seprator. But no matter what I select it only passes me the value for the first item in the list box whether its selected or not selected.

Here an example

List box1

item1    selected
item2    selected
item3
item4     selected
item5
item6     selected.

out of the four items that are selected it will only pass the value of item1 in variable.

here is the code that i am using

  For i = 1 To listbox1.Items.Count
            If listbox1.Items(i - 1).Selected = True Then
                strsub = strsub & "," & listbox1.items(i-1).Text
            End If
        Next
pratikshahseAsked:
Who is Participating?
 
Arthur_WoodCommented:
Try this change in your Page_Load even handler:

If Not IsPostBack = True Then
           
            cn = New OracleConnection(ConfigurationSettings.AppSettings("connectionstring"))
            sql = "select item_family_brand_text,item_family_brand_code from sads4a.tbl_family_brand order by item_family_brand_text "
            mycommand = New OracleDataAdapter(sql, cn)
            mydataset = New DataSet
            mycommand.Fill(mydataset)

            With drpbrand_nm
                  .DataSource = mydataset
                  .DataValueField = "item_family_brand_code"
                  .DataTextField = "item_family_brand_text"
                  .DataBind()
            End With
           

            mycommand.Dispose()
            mydataset.Dispose()
Else
            Dim brand As String = drpbrand_nm.SelectedValue

            sql = "select item_family_brand_code,item_brand_text from sads4a.tbl_brand where item_family_brand_code = '" & brand & "'"
            mycommand = New OracleDataAdapter(sql, cn)
            mydataset = New DataSet
            mycommand.Fill(mydataset)

            With listbox1
                 .DataSource = mydataset
                 .DataValueField = "item_family_brand_code"
                 .DataTextField = "item_brand_text"
                 .DataBind()
            End With

            mycommand.Dispose()
            mydataset.Dispose()
End If

AW
0
 
Arthur_WoodCommented:
show us ALL of the code in the Page_Load routine in your code-behind.

AW
0
 
pratikshahseAuthor Commented:
 If Not IsPostBack = True Then
            Dim brand As String
            cn = New OracleConnection(ConfigurationSettings.AppSettings("connectionstring"))
            sql = "select item_family_brand_text,item_family_brand_code from sads4a.tbl_family_brand order by item_family_brand_text "
            mycommand = New OracleDataAdapter(sql, cn)
            mydataset = New DataSet
            mycommand.Fill(mydataset)
            drpbrand_nm.DataSource = mydataset
            drpbrand_nm.DataValueField = "item_family_brand_code"
            drpbrand_nm.DataTextField = "item_family_brand_text"
            drpbrand_nm.DataBind()
           

            mycommand.Dispose()
            mydataset.Dispose()

            brand = drpbrand_nm.SelectedValue

            sql = "select item_family_brand_code,item_brand_text from sads4a.tbl_brand where item_family_brand_code = '" & brand & "'"
            mycommand = New OracleDataAdapter(sql, cn)
            mydataset = New DataSet
            mycommand.Fill(mydataset)
            listbox1.DataSource = mydataset
            listbox1.DataValueField = "item_family_brand_code"
            listbox1.DataTextField = "item_brand_text"
            listbox1.DataBind()
            mycommand.Dispose()
            mydataset.Dispose()
        End If

0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
SStoryCommented:
The following code:

Public Class WebForm1
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ListBox1 As System.Web.UI.WebControls.ListBox
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim item As ListItem
        Dim s As String = String.Empty

        For Each item In ListBox1.Items
            If item.Selected Then
                If s <> String.Empty Then
                    s &= ","
                End If
                s &= item.Text
            End If
        Next

        Response.Write("Results=" & s)
    End Sub
End Class

worked great for me.

I selected A,C, and D
The results screen showed:

Results=A,C,D

HTH,

Shane
0
 
Arthur_WoodCommented:
I added a button to a web form, and a ListBox, with Mode set to Multiple.

In the Code Behind, I have thsi code:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strsub As String
        For i As Integer = 1 To ListBox1.Items.Count
            If ListBox1.Items(i - 1).Selected = True Then
                strsub = strsub & "," & ListBox1.Items(i - 1).Text
            End If
        Next
        Label1.Text = strsub


    End Sub

and the label control shows the expected result, when multiple itmes from the ListBox are selected.



AW
0
 
nayernaguibCommented:
Set the AutoPostBack property of the listbox to true.

_______________

  Nayer Naguib
0
 
nayernaguibCommented:
SStory: When you have some "harcoded" items in the listbox, you do not need to set the AutoPostBack property to true. That's why your code worked.

_______________

  Nayer Naguib
0
 
nepostojeci_emailCommented:
pratikshahse, the main problem was that the http request with the multiselect
listbox looks like this:

GET /bla.asp?select1=h1&select1=h3&select1=h4&select1=h6 HTTP/1.1
Accept: ...
Accept-Language: ...
Accept-Encoding: ...
User-Agent: ...
Host: ...
Connection: ...

with the html like:

      <SELECT name=select1 multiple>
            <option selected>opt1</option>
            <option>opt2</option>
            <option selected>opt3</option>
            <option selected>opt4</option>
            <option>opt5</option>
            <option selected>opt6</option>
      </SELECT>

that means the request contains repeated "name=value" pairs with the same
name string:

"GET /bla.asp?select1=h1&select1=h3&select1=h4&select1=h6 HTTP/1.1"
(select1=h1 & select1=h3 & select1=h4 & select1=h6 )

If you don't find the way how to get the selected items, the last solution would
be to check the raw url, and to split those name=value pairs into your comma
separated list.
0
 
nepostojeci_emailCommented:
h1, h2, h3 are actually opt1, opt2, opt3...

a typo.. sorry..
0
 
SStoryCommented:
I posted before I'd seen the author show the loading code. I didn't know it was coming from a database based on the original question.
0
 
pratikshahseAuthor Commented:
AW

if i use your code then it does not even go inside "if". everytime i select something and hit button1 it would reload the page with nothing selected.
0
 
pratikshahseAuthor Commented:
Nayer Naguib

I tried making autopostback = true but that wont allow me to insert more than one item.
0
 
FocusynCommented:
Three settings on your listbox are important: SelectionMode = SelectionMode.Multiple | AutoPostBack=True | EnableViewState=True

EnableViewState=True is what maintains selection state across postback(s)

I just whipped up a page that binds a listbox from a SQL stored proc that returns ten most recent updates to a table, then rather than concatenating a string, enters each value and a vbCrLf in a multiline textbox (just so I could more easily see the correlation in testing).  Here's my code, which works perfectly on this end.

Imports System.Data.SqlClient
Public Class WebForm6
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents tb1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents lbtest As System.Web.UI.WebControls.ListBox

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            lbtest.AutoPostBack = True
            lbtest.SelectionMode = ListSelectionMode.Multiple
            Dim sCon As New SqlConnection(ConfigurationSettings.AppSettings("sConVMLoadTest"))
            Dim sCmd As New SqlCommand("[sp_LastTenUpdates]", sCon)
            sCmd.CommandType = CommandType.StoredProcedure
            sCon.Open()
            lbtest.DataSource = sCmd.ExecuteReader
            lbtest.DataMember = 0
            lbtest.DataTextField = ("tmUpdate").ToString
            lbtest.DataValueField = ("tmStart").ToString
            lbtest.DataBind()
            sCon.Close()
        End If

        Dim i As Integer
        tb1.Text = ""
        For i = 0 To (lbtest.Items.Count - 1)
            If lbtest.Items(i).Selected = True Then
                tb1.Text &= lbtest.Items(i).Text & vbCrLf
            End If
        Next

    End Sub

End Class
0
 
FocusynCommented:
I'm sorry - in my last post, on the first line I wrote
 SelectionMode=SelectionMode.Multiple

That should have read
SelectionMode=ListSelectionMode.Multiple


It's correct in my code sample, as I copied/pasted that directly from Visual Studio, but didn't want you skimming over, typing that in and getting intellisense errors etc...
0
 
nayernaguibCommented:
I have written similar code that does the job, and did not have to set EnableViewState to true. First, it's set to true by default. Second, having this property set to false *clears* the whole listbox after postbacks!

Having the SelectionMode set to Multiple is the only other requirement, which the author has already done.

_______________

  Nayer Naguib
0
 
nayernaguibCommented:
pratikshahse: To avoid this behavior of the ASP .NET listbox control, you need to make sure that all added items will have unique Text **and** Value property values.

_______________

  Nayer Naguib
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.