NoNo
NoNo

Reputation: 313

vb 2010 checkbox loop

So I'm trying to get this permission app going. I'm stuck in that I want to have the string adkey be the name of the checkbox as in "cbo" & adkey. so that the same string will the name of the check box. I got kinda mad and copied the whole thing here so its kind of a mess.

Dim ADkey As String() =
        {"NoChangingWallpaper", "NoHTMlWallpaper"}
    ' Dim cbo As String = 
    Dim cho As CheckBox
    cho = CType("cbo" & ADkey), CheckBox)
    Dim readvalue = My.Computer.Registry.GetValue(
        "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\ActiveDesktop", ADkey, Nothing)
    'MsgBox("The value is " & CStr(readValue))
    ' Dim cho(ADkey) As CheckBox
    cho.Name = ADkey
    If readvalue = "1" Then
        cho.Checked = True
    Else
        cho.Checked = False
    End If

the msgbox portion was for testing

Upvotes: 0

Views: 355

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

You should add all your checkboxes to a Dictionary(Of String, Checkbox) object:

Dim ADkey As String() =
    {"NoChangingWallpaper", "NoHTMlWallpaper"}

'This code can move to where the checkboxes are first created, as long as you can reach the variable from here
Dim checkboxes As New Dictionary(Of String, Checkbox) From 
  {
     {"NoChangingWallpaper", cboNoChangingWallpaper},
     {"NoHTMlWallpaper", cboNoHTMLWallpaper}
  }

For Each key As String in ADKey.Where(Function(k) checkboxes.ContainsKey(k))
    Dim regvalue As Boolean = (My.Computer.Registry.GetValue(
    "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\ActiveDesktop", key, Nothing)="1")
    Dim box As Checkbox = checkboxes(key)
    box.Name = key
    box.Checked = regvalue
Next Key

And as I look at this, to avoid keeping double records of the keys I might cut out the string array entirely and do it like this:

'This code can move to where the checkboxes are first created, as long as you can reach the variable from here
Dim checkboxes As New Dictionary(Of String, Checkbox) From 
  {
     {"NoChangingWallpaper", cboNoChangingWallpaper},
     {"NoHTMlWallpaper", cboNoHTMLWallpaper}
  }

For Each key As String in checkboxes.Keys
    Dim regvalue As Boolean = (My.Computer.Registry.GetValue(
"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\ActiveDesktop", key, Nothing)="1")
    Dim box As Checkbox = checkboxes(key)
    box.Name = key
    box.Checked = regvalue
Next Key

Whether or not you want this version depends on whether you're always looking at all the boxes, or whether you might something only want to update certain ones.

Upvotes: 1

Related Questions