Reputation: 19
I'm not sure why I'm getting a warning from Visual Studio for the code below:
Dim cmd As SqlCommand
cmd.Parameters.AddWithValue("@password", pw.tostring)
Try
myconn.open
cmd = New SqlCommand("UPDATE Customers SET PW2=@password WHERE ID=@id", myconn)
This is the warning message I get:
Severity Code Description Project File Line Suppression State
Warning BC42104 Variable 'Cmd' is used before it has been assigned a value. A null reference exception could result at runtime.
Appreciate any help
Upvotes: 0
Views: 95
Reputation: 65806
You are accessing the Parameters property of cmd:
Dim cmd As SqlCommand
cmd.Parameters.AddWithValue("@password", pw.tostring) ' <== You can't use cmd yet!
before you instantiate it in the try:
Try
myconn.open
' This is where you are instantiating the object instance:
cmd = New SqlCommand("UPDATE Customers SET PW2=@password WHERE ID=@id", myconn)
If you change to this, it will work:
Dim cmd As SqlCommand
cmd = New SqlCommand("UPDATE Customers SET PW2=@password WHERE ID=@id", myconn)
' You could combine the two above lines into one like this:
'Dim cmd As New SqlCommand("UPDATE Customers SET PW2=@password WHERE ID=@id", myconn)
cmd.Parameters.AddWithValue("@password", pw.tostring)
Try
myconn.open
This is also better, because only the myconn.open
instruction should be in the Try/Catch since it is the only line that can cause an exception. Try/Catch should only be used around code that can cause an exception through no fault of the developer's. Adding a parameter to a command won't do that, but actual database interaction can.
Upvotes: 3