Results 1 to 16 of 16

Thread: [RESOLVED] ListBox Selected Values to String()

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Resolved [RESOLVED] ListBox Selected Values to String()

    Hello all,

    I am developing a Webpage that gives the user selection criterial before running a report. There is a asp.net ListBox that I need to get the selected values from. It is obviously a multi select listbox.

    I need to pass the selected values as a comma separated string to a parameter used in an SQL query of the ObjectDataSource for the report. I was hoping some how to get the selected items, and load their value into a string array and then use the join( stringArray , "," ) to get the selected values into a string to send as a parameter to my objectdatasource but I cant seem to figure this out..

    Ideally if code worked my way I would want to do something like this:

    Declare StringArray

    for each selected item in Mylistbox
    Add selected value to StringArray

    Set parameter = join( StringArray , "," )


    Obviously this is what I need syntax for.. I pretty much just need to know how to get a string array or all selected values. Any ideas?

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: ListBox Selected Values to String()

    I haven't used ASP, but in the Windows Listbox there is a SelectedItems list, which is alreayd a collection. I would expect that you can use .ToArray on that to turn it into a string array. However, this won't necessarily work unless your listbox is just displaying a list of strings. If you have it bound to a datatable, then the return from SelectedItems may not be useable in that fashion. In that case, you could use LINQ to get the values if you are working in .NET 3.5 or higher.

    Since I am off into the speculative weeds at this point, I won't go further at this time. Try the SelectedItems.ToArray to see if that gets you what you need, and if not, then state what version of the framework you are targeting.
    My usual boring signature: Nothing

  3. #3
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: ListBox Selected Values to String()

    Are you using asp.net?

    Try this:
    (not tested but should work in both asp as well as asp.net)
    vb Code:
    1. Dim selectedItems as String = Request(MyListBox)
    2.  
    3. 'selectedItems should now have a comma separated list of selected items.
    4. 'lets test
    5. Response.Write(selectedItems)
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  4. #4

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    I am using Visual Web Developer 2008. It uses version 3.5 of the .NET framework.

    I really like Pradeep1210's solution but I can't get it to work. I get the following error:

    Value of type 'System.Web.UI.WebControls.ListBox' cannot be converted to 'String'

    It underlines the ChooseNDR object name.

    I don't know much about ASP.Net or Vb.net or anything. I just have a code behind file for my webform. It has Ajax.controls associated to it if thats what your asking? If it helps, this is the code behind for my webform:

    Code:
    <%@ Page Language="VB" %>
    
    <%@ Register assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" namespace="Microsoft.Reporting.WebForms" tagprefix="rsweb" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
                
            'This is where I am writing my code in VB
            Dim selectedItems As String = Request(ChooseNDR)
    
            Label1.Text = selectedItems
            
            Dim RDS As New ReportDataSource
            RDS.DataSourceId = "ObjectDataSource1"
            RDS.Name = "Database_JobGroups"
            ReportViewer1.LocalReport.DataSources.Clear()
            ReportViewer1.LocalReport.DataSources.Add(RDS)
            ReportViewer1.LocalReport.Refresh()
            ReportViewer1.Visible = True
    
    End Sub
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <style type="text/css">
            .style1
            {
                height: 335px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div class="style1">
        
            <span lang="en-ca">Choose NDR list:<br />
            </span>
                        <asp:ListBox ID="ChooseNDR" runat="server" SelectionMode="Multiple" 
                            Width="312px" Height="121px" DataSourceID="NDRCodeDS" DataTextField="JobCode" 
                            DataValueField="JobCodeID" AppendDataBoundItems="True">
                            <asp:ListItem Value="-1">All</asp:ListItem>
                        </asp:ListBox>
                    <br />
            <br />
            <span lang="en-ca">Hit this to display report:</span><br />
            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" 
                Width="155px" />
        
            <br />
            <br />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        
        </div>
        <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" 
            Font-Size="8pt" Height="400px" Width="100%">
            <LocalReport ReportPath="ztest.rdlc">
            </LocalReport>
        </rsweb:ReportViewer>
        <asp:ObjectDataSource ID="NDRCodeDS" runat="server" 
            OldValuesParameterFormatString="original_{0}" 
            SelectMethod="GetJobGroupsDataByActive" 
            TypeName="DatabaseTableAdapters.JobGroupsTableAdapter">
        </asp:ObjectDataSource>
        <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
            OldValuesParameterFormatString="original_{0}" 
            SelectMethod="GetJobGroupDataByJobCodeID" TypeName="JobGroupBLL">
            <SelectParameters>
                <asp:ControlParameter ControlID="ChooseNDR" Name="JobCodeID" 
                    PropertyName="SelectedValue" Type="Int32" />
            </SelectParameters>
        </asp:ObjectDataSource>
        </form>
    </body>
    </html>

  5. #5

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    I got it working with the following code, but would really like to simplify it down to how you have described with this Request() thinger. Also yes I am using ASP.NET cause the page ends with .aspx

    vb Code:
    1. Label1.Text = ""
    2.         Dim selectionList As New System.Collections.Generic.List(Of String)
    3.        
    4.  
    5.         For Each itm As ListItem In ChooseNDR.Items
    6.             If itm.Selected = True Then
    7.                 selectionList.Add(itm.Value)
    8.             End If
    9.         Next
    10.        
    11.         Label1.Text = String.Join(",", selectionList.ToArray)

  6. #6

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    I dont know why my other post didn't go through but I am developing with the following:

    -Visual Web Developer 2008
    -.Net frame work 3.5
    -Designing a Web Form with AJAX controls and VB code behind

  7. #7
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: ListBox Selected Values to String()

    What happens if you replace that code with this one line:

    Code:
    Label1.Text = Request("ChooseNDR")

  8. #8
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: ListBox Selected Values to String()

    Thread moved from the 'VB.Net' forum to the 'ASP.Net' forum
    Quote Originally Posted by Hybird View Post
    I dont know why my other post didn't go through
    Part of our anti-spam system puts some posts from newer members in a queue to be manually approved, and I have now approved it so it is shown above.

  9. #9

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    Wow... simply wow. Thank you so much, you have no idea how easy that has made things for me!

  10. #10

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    Quick editition, is there a way to get all the values into a comma separated list even if they are not selected? I want to do something along the lines of this:

    vb Code:
    1. If ChooseNDR.SelectedItem.Value = -1 Then
    2.             Label1.Text = Request("ChooseNDR")
    3.         Else
    4.             Label1.Text = String.Join(",", ChooseNDR.SelectedValue.ToArray)
    5.         End If
    6.  
    7.  
    8. End If

    Obviously again my sytax is wrong on the Join() part, but is there something that can be done to do this? I have a appended item called ALL where it should pull all values from the list.

  11. #11
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: ListBox Selected Values to String()

    NO, for that you will have to loop thru the list items.
    But consider this: The source from where you filled that list must already have all the items in the first place. So cant you use the same source?
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  12. #12
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    Re: ListBox Selected Values to String()

    From what you indicated in your earlier posts, you are using .net 3.5
    So you can use LINQ to simplify things.

    (again not tested code, but should work)
    vb.net Code:
    1. Dim allListItems = From li in ChooseNDR.Items Select li.value
    2. Label1.Text = Join(allListItems.ToArray, ",")
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

  13. #13
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: ListBox Selected Values to String()

    Just a thought...

    Where are you populating the ListBox? Does this happen in the ASPX markup, or are you DataBinding the ListBox somewhere else. I only ask because, if this is a fixed ListBox, you already know this information ahead of time, so you might not have to loop through all the items contained within it. Or, if you are DataBinding, you could create the string at the time of DataBinding.

    Gary

  14. #14

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    Thanks, I will take a look at that LINQ stuff. As for how the data is getting populated... This project involves creating a frontpage for a rather complex database. So when I am populating the listbox I am databinding it to an objectdatasource that is connected to the database, so I am doing this in ASP.net I would guess. I then add an option of 'All' in the VB markup as an appended item to the list. So no, I do not have an all option in the dataset. And this list box is cascaded off of another selection, so the values can change as we select different stuff.

    I am building a front page for a report, and I send back a comma separated string to a table valued function which generates a table of all the values in the string. I then Join to that table in my query to get the possible selections. In order for the all option to work, I have to send all the possible selections to that function.

    Before I was doing some boolean algebra in the WHERE clause of my query such as :

    WHERE (cityID = @cityID OR @cityID = -1)

    because -1 is never an id of that field, and hence it would return all. But I have read this is bad for performance of stored procs, and also the client wants to be able to send multiple values. So thats a bit of an overview.

  15. #15

    Thread Starter
    New Member
    Join Date
    Sep 2010
    Posts
    8

    Re: ListBox Selected Values to String()

    Quote Originally Posted by Pradeep1210 View Post
    From what you indicated in your earlier posts, you are using .net 3.5
    So you can use LINQ to simplify things.

    (again not tested code, but should work)
    vb.net Code:
    1. Dim allListItems = From li in ChooseNDR.Items Select li.value
    2. Label1.Text = Join(allListItems.ToArray, ",")
    Thank you again, this does work fine. Just to clarify, this is what I ended up with.

    vb.net Code:
    1. 'This is done on the 'On_click' event of a button. Printing the values to
    2. 'a label is done solely for testing purposes. Really I'd send them to a parameter
    3.         Dim allListItems = From li In ChooseNDR.Items Select li.value
    4.         Label1.Text = ""
    5.        
    6.         If ChooseNDR.SelectedItem.Value = -1 Then
    7.             Label1.Text = Join(allListItems.ToArray, ",")
    8.         Else
    9.             Label1.Text = Request("ChooseNDR")
    10.         End If

  16. #16
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: ListBox Selected Values to String()

    Sounds like you have got a working solution

    Can you remember to mark your thread as resolved?

    Thanks

    Gary

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width