Visual Basic警告

时间:2016-01-25 15:00:13

标签: mysql vb.net

我收到了3个警告。我想知道任何解决方法,提前谢谢!

警告:

警告1变量' Id_Utilizador'在被赋值之前使用。在运行时可能会导致空引用异常。 C:\ Users \ tiago \ Desktop \ Portaria \ Portaria_Programa \ Portaria_Programa \ frmAdmin_NewEdit.vb 332 37 Portaria_Programa

警告2变量' Id_Modulo'在被赋值之前使用。在运行时可能会导致空引用异常。 C:\ Users \ tiago \ Desktop \ Portaria \ Portaria_Programa \ Portaria_Programa \ frmAdmin_NewEdit.vb 332 60 Portaria_Programa

警告3变量' DadosSai'在被赋值之前使用。在运行时可能会导致空引用异常。 C:\ Users \ tiago \ Desktop \ Portaria \ Portaria_Programa \ Portaria_Programa \ frmRel_EntradasSaidas.vb 222 37 Portaria_Programa

代码:

Private Sub NovoAcesso()

    Dim Id_Utilizador
    Dim Id_Modulo

    Dim Count

    If (cmbUtilizadores.Text <> "") Then

        If (cmbModulos.Text <> "") Then

            Cn.Open(cStringCon)
            Rs.Open("Select count(id_utilizador), id_utilizador from acessos_utilizadores where nome_utilizador like '" & cmbUtilizadores.Text & "'", Cn)

            Count = Rs.GetRows

            Rs.Close()

            If (Count(0, 0) > 0) Then

                Id_Utilizador = Count(1, 0)

                Rs.Open("Select count(id_modulo), id_modulo from acessos_modulos where nome_modulo like '" & cmbModulos.Text & "'", Cn)

                Count = Rs.GetRows

                Rs.Close()

                If (Count(0, 0) > 0) Then

                    Id_Modulo = Count(1, 0)

                    Rs.Open("Select count(id_acesso) from acessos_acessos where id_utilizador = " & Id_Utilizador & "", Cn)

                    Count = Rs.GetRows

                    Rs.Close()

                    If (Count(0, 0) > 0) Then

                        Msg = "O utilizador seleccionado já dispõe de um acesso."

                    End If

                Else

                    Msg = "Seleccione um módulo da lista."

                End If

            Else

                Msg = "Seleccione um utilizador da lista."

            End If

            Cn.Close()

        Else

            Msg = "Seleccione um módulo da lista."

        End If

    Else

        Msg = "Seleccione um utilizador da lista."

    End If

    If (Msg = "") Then

        Cn.Open(cStringCon)

        Cn.Execute("Insert into acessos_acessos(id_utilizador,id_modulo) " & _
                   "values (" & Id_Utilizador & ", " & Id_Modulo & ")")

        Cn.Close()

        ActGrid = 1

    End If

    Count = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

Id_UtilizadorId_Modulo在使用时可能没有值。 (值DadosSai不在此代码中,但听起来它具有相同的风险。)

这是因为你不是总是为它们分配值。为了说明,请考虑这个简化版本:

Dim SomeValue
If SomethingElse = True Then
    SomeValue = SomeOtherValue
End If
UseTheValue(SomeValue)

如果SomethingElse不是True,此代码会做什么?没有任何东西可以分配给变量,它可能很容易破坏使用它的功能。

使用默认值初始化变量,或者确保所有逻辑路径在使用之前为它们赋值。