Question

Problem: I'd like to retrieve the name of a checkbox from a SQL Server database table and see whether it's checked in an "if" statement.

Interface: my form consists of a listbox, a button and a checkbox.

SQL Server table:

ID   Name   cbName
 1   Rest   cbRest

I'd like to write:

sb = dt.rows(0)(cbName) 
    If sb.Checked() = True Then
        ListBox1.Items.Add(dt.Rows(0)(1).ToString())
    Else
        MsgBox("Nothing checked")
    End If

The expected output should be Rest in the listbox. Of course the next step is to loop through hundreds of checkboxes but for now I'd just like to clarify how to make this work.

Right now I get the following error:

Unable to cast object of type 'System.String' to type 'System.Winddows.Forms.CheckBox'

I'm using Visual Basic Express 2008 with SQL Server 2008 Express, 64 bit Windows 7 Pro

Thanks in advance

Was it helpful?

Solution

Assuming you have added your check box directly to the page you can find controls by name using Me.Controls.Item(controlID), so in your case it would be

Dim sb as CheckBox = CType(Me.Controls.Item(dt.rows(0)("cbName")), CheckBox)

OTHER TIPS

You will have to loop through all your controls and find the control with id/name [cbRest]. As soon as you get hand on the control (which is a checkbox) you can use

If sb.Checked() = True Then
    ListBox1.Items.Add(dt.Rows(0)(1).ToString())
Else
    MsgBox("Nothing checked")
End If

where sb will be the control you found.

You need to declare a variable (sb) Here's a snippet for a button:

Dim btn As Button 
...
btn = CType(Controls("Button1"), Button)

In your case you will use the cbName value from SQL in place of "Button".

'Controls' is the parent holding the button/checkbox. The snippet works with a button on the form. If you have a container holding the checkboxes use the container_name.Controls().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top