CheckedListBox - return a ValueMember

peropero

New member
Joined
Aug 16, 2005
Messages
2
Programming Experience
10+
Hi,

I feel the checkedlistbox trought this code:

Dim ds As New DataSet
Dim da As New SqlClient.SqlDataAdapter
Dim cnnSQLString As String = "server=mysqlserver; database=mysql; uid=aaaa; pwd = pwdddd;"
Dim SQLString As String = "SELECT pr_oz, pr_opis FROM prSredstvo"
Dim conn As SqlConnection = New SqlConnection(cnnSQLString)
da.SelectCommand =
New SqlCommand
da.SelectCommand.Connection = conn
conn.Open()
da.SelectCommand.CommandText = SQLString
'clbProfitniCentri is CheckedListBox
Try
da.Fill(ds, "oe")
clbProfitniCentri.DataSource = ds.Tables(0)
clbProfitniCentri.DisplayMember = ds.Tables("oe").Columns("pr_opis").ToString
clbProfitniCentri.ValueMember = ds.Tables("oe").Columns("pr_oz").ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try

I would like to read a ValueMember of all checked items in my CheckedListBox.

tnx...
brg.,
PeroPero

 
Loop through items

The Tag property in databindings of the checkbox are bound to a field in a dataset: When you check a box you are marking a row of the dataset. I loop through the items, if it is checked I get the corresponding row of a datatable so I have access to all the fields.

VB.NET:
 Dim counter As Integer
For counter = 0 To clbCheckBox1.Items.Count - 1
     If clbCheckBox1.GetItemChecked(Counter) = True Then
         Dim tblTest1 As DataTable
         tblTest1 = DsTable1.Tables("Table Name")
         Dim drCurrentRow As DataRow
         drCurrentRow = tblTest1.Rows(counter)
         'Set variables to values in the current row of a datatable
    End If
Next counter
 
VB.NET:
For Each item As DataRowView In myCheckedListBox.CheckedItems
    MessageBox.Show(item(myCheckedListBox.ValueMember).ToString())
Next item
When a control is bound to a DataTable each item is a DataRowView, which behaves somewhat like a DataRow. The ValueMember contains the name of a column so you can use it to index the DataRowViews to get the value in that column.
 
Also note that this is wrong:
VB.NET:
[SIZE=2] clbProfitniCentri.DisplayMember = ds.Tables("oe").Columns("pr_opis").ToString
clbProfitniCentri.ValueMember = ds.Tables("oe").Columns("pr_oz").ToString[/SIZE]
The DisplayMember and ValueMember are the names of columns and you are specifying them already. Just use this:
VB.NET:
[SIZE=2] clbProfitniCentri.DisplayMember = "pr_opis"
clbProfitniCentri.ValueMember = "pr_oz"[/SIZE]
 
Further to my previous post, what you were originally doing was not strictly wrong as it would still have returned the ColumnName, but it was a very roundabout way to do it. Also note that calling ToString on a DataColumn does not always return the ColumnName. If that column has an Expression it will return that in preference.
 
Back
Top