Consider :
Private Function isAvailableQuantity() As Boolean
Try
sqL = "SELECT StocksOnHand FROM ITEM WHERE ItemNo = " & Val(txtSearch.Text) & ""
ConnDB()
cmd = New OleDbCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
If dr.Read = True Then
If Val(txtQuantity.Text) <= dr(0) Then
isAvailableQuantity = True
Else
MsgBox("Insuficient stocks", MsgBoxStyle.Critical, "Validate Stocks")
txtSearch.Clear()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Function
I don't know what to do. The older version visual studio doesn't get this error. i am using vs 2022 right now and it seems to have an error on the contrary vs 2010 doesn't
CodePudding user response:
In VB.NET, a Function
is a method that returns a value and a Sub
is a method that doesn't return a value. If your method doesn't need to return anything, use a Sub
, e.g.
Private Sub DoSomething()
'Do some stuff here.
End Sub
If you do use a Function
then there are two ways to return a value. The bad way is to assign a value to the implicit local variable that is named after the method, e.g.
Private Function DoSomething() As Boolean
'Do some stuff here.
DoSomething = True
End Function
That way basically only exists to support upgraded VB6 code. If your teacher is showing you that then they are obviously an old VB6 developer who hasn't actually learned VB.NET properly. The good way to return a value is with an explicit Return
statement, e.g.
Private Function DoSomething() As Boolean
'Do some stuff here.
Return True
End Function
If there are multiple paths that execution could take through your code, you need to make sure that a value is returned on all of them. As an example, this code does not do that:
Private Function DoSomething() As Boolean
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
Return True
End If
End Function
That will return True
on Mondays but it doesn't return anything on other days. In this specific case, one fix would be this:
Private Function DoSomething() As Boolean
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
Return True
End If
Return False
End Function
If you are going to use the bad way to return a value and you want to return a particular value on all but one code path then the logical thing to do is to set the return value at the start to the default and then only change it in that one place, e.g.
Private Function DoSomething() As Boolean
DoSomething = False
If Date.Now.DayOfWeek = DayOfWeek.Monday Then
DoSomething = True
End If
End Function
That last example is the easiest (although not best) fix for your scenario.