Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

multi line select in list box in asp.net

Posted on 2006-03-31
16
Medium Priority
?
2,882 Views
Last Modified: 2008-01-09
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
0
Comment
Question by:pratikshahse
  • 4
  • 3
  • 3
  • +3
16 Comments
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 16344278
show us ALL of the code in the Page_Load routine in your code-behind.

AW
0
 

Author Comment

by:pratikshahse
ID: 16344358
 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
 
LVL 25

Expert Comment

by:SStory
ID: 16344370
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 16344411
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
 
LVL 44

Accepted Solution

by:
Arthur_Wood earned 2000 total points
ID: 16344479
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
 
LVL 14

Expert Comment

by:nayernaguib
ID: 16344540
Set the AutoPostBack property of the listbox to true.

_______________

  Nayer Naguib
0
 
LVL 14

Expert Comment

by:nayernaguib
ID: 16344593
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
 
LVL 8

Expert Comment

by:nepostojeci_email
ID: 16344697
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
 
LVL 8

Expert Comment

by:nepostojeci_email
ID: 16344703
h1, h2, h3 are actually opt1, opt2, opt3...

a typo.. sorry..
0
 
LVL 25

Expert Comment

by:SStory
ID: 16344719
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
 

Author Comment

by:pratikshahse
ID: 16345193
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
 

Author Comment

by:pratikshahse
ID: 16345207
Nayer Naguib

I tried making autopostback = true but that wont allow me to insert more than one item.
0
 
LVL 7

Expert Comment

by:Focusyn
ID: 16346198
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
 
LVL 7

Expert Comment

by:Focusyn
ID: 16346239
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
 
LVL 14

Expert Comment

by:nayernaguib
ID: 16346328
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
 
LVL 14

Expert Comment

by:nayernaguib
ID: 16348299
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Progress
Introduction to Processes

810 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