I am trying to have a checkedlist box with values loaded at run time. But when I try to get checked values from it. it returns the following error:
Operator '&' is not defined for string '' and type 'DataRowView',
Though when I load the checkedlistbox at desigh it works fine
Public Sub loadListBox(ByVal lst As CheckedListBox, ByVal sql As String, ByVal fldDsp As String, ByVal fldVal As String)
Try
'open DB Connection
openConn()
Dim lstDS As New DataTable
Dim lstAD As SqlDataAdapter
Dim cboCMD As New SqlCommand(sql, Qconn)
lstAD = New SqlDataAdapter(sql, Qconn)
lstAD.Fill(lstDS)
lst.Items.Clear()
lst.SelectedIndex = -1
With lst
.Items.Clear()
.DataSource = Nothing
.Text = fldDsp
.DataSource = lstDS
.ValueMember = fldVal
.DisplayMember = fldDsp
End With
Catch ex As Exception
msgError("ERROR:Failed Loading Values " ex.Message)
Exit Sub
Finally
closeConn()
End Try
End Sub
---on form load
Dim symp As String = "SELECT distinct facility FROM [eLab].[settings].[Locations]"
frm.chk_locations.Items.Clear()
loadListBox(frm.CheckedListBox1, symp, "facility", "facility")
Public Function getCheckedItems(ByVal chk As CheckedListBox) As String
Dim items As String = ""
If chk.CheckedItems.Count > 0 Then
items = "" & chk.CheckedItems(0) & ""
'check if the checked items are more than 1
If chk.CheckedItems.Count > 1 Then
For i As Integer = 1 To chk.CheckedItems.Count - 1
items = items & "," & chk.CheckedItems(i) & ""
Next
End If
End If
Return items
End Function
Dim configlocation As String = getCheckedItems(frm.CheckedListBox1)
msgBox(configlocation)
what I was Expecting is LocationA,Location X (alls selected locations comma separated
CodePudding user response:
When you bind a DataTable
to a control, the data comes from its DefaultView
, which is type DataView
, which is a list of DataRowView
objects. That means that each item in the control is a DataRowView
, so obviously every checked item is a DataRowView
. If what you actually want is the text displayed for each item then you need to call the GetItemText
method of the control. If what you want is a comma-delimited string containing the text of the check ed items, this is what you should do:
Dim items = String.Join(",",
chk.CheckedItems.
Cast(Of Object)().
Select(Function(item) chk.GetItemText(item)))
That uses LINQ to get a list of checked items, get the a list of the text of those items, then join that list into s ingle comma-delimited String
.