Link to home
Start Free TrialLog in
Avatar of bgernon
bgernonFlag for United States of America

asked on

Retrieve checkedlistbox values into a comma deliniated string

I've been struggling to retrieve the values of the checked items from a checkedlistbox.  I need to place the values into a comma delineated string to use in a sql query.  I'd done a similar thing with a datagridview.  I tried to apply the same logic, with no success.  I thought I had found the answer at:

https://www.experts-exchange.com/questions/21143011/How-to-retrieve-checked-values-from-databound-checkedlistbox-windows-vb-net.html

The line IDString &= chkOperID.SelectedValue & "," gives me an error:  Variable 'IDString' is used before it has been assigned a value.  A null reference exception could result at runtime.

Help!
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

That's a warning not an error. You can simply initialize it where you declare it

Dim IDString As String = ""
Avatar of bgernon

ASKER

Tried that already.  All I get is a string of commas.
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bgernon

ASKER

Sorry?  This question is still open.  

Anyway, we're getting closer.  I now have a comma delineated string.  Just have to put the parentheses at the beginning and end.  I think I know how.  Will play with it some more.
Avatar of bgernon

ASKER

Success!  

Dim IDString As String = "("
        Dim i As Integer
        For Each i In chkOperID.CheckedIndices
            chkOperID.SelectedIndex = i
            IDString &= chkOperID.Items(i) & ","
        Next
        IDString = IDString.Substring(0, IDString.LastIndexOf(",")) + ")"

A messagebox shows the string I needed to place in my query.  

Thanks CodeCruiser.
Avatar of bgernon

ASKER

Thanks
Avatar of bgernon

ASKER

I did not need  ' chkOperID.SelectedIndex = i'.  I commented it out.
Glad to help :-)