System.NullReferenceException when trying to read registry key VisualBasic

331 Views Asked by At

I'm trying to make the checkbox filled when Launcher_SessionLoginAnimation_OnShow is set to 1. I can't seem to fix a problem which is causing a System.NullReferenceException. I tried searching google and stackexchange, but I couldn't find a solution.

Imports Microsoft.Win32
Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim subKeyName As String = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ImmersiveShell\\Grid"
        Dim key As RegistryKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(subKeyName)
        If key IsNot DBNull.Value Then
            Dim readValue As String = key.GetValue("Launcher_SessionLoginAnimation_OnShow")
            If readValue.Equals("1") Then
                CheckBox1.Checked = True
            End If
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked = True Then
            Dim key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                  "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ImmersiveShell\\Grid", True)
            If key IsNot Nothing Then
                key.SetValue("Launcher_SessionLoginAnimation_OnShow", 1)
                key.Close()
            End If
        Else
            Dim key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
                  "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ImmersiveShell\\Grid", True)
            If key IsNot Nothing Then
                key.SetValue("Launcher_SessionLoginAnimation_OnShow", 0)
                key.Close()
            End If
        End If
    End Sub
End Class

Where readValue As String = key.GetValue("Launcher_SessionLoginAnimation_OnShow") throws System.NullReferenceException Can anyone help me fix this problem? Any help is appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

This line is wrong:

If key IsNot DBNull.Value Then

DBNull.Value is used for SQL database results, and not for registry keys. Try this instead:

If key IsNot Nothing Then