Arnold Barrozo Arnold Barrozo - 1 year ago 76 Question

FieldValue is not returning

Sub GetData(ByVal SelectedColumn As String, ByVal Table As String, ByVal ConditionField As String, ByVal ConditionValue As String, ByVal FieldValue As Integer)
con.Open() Query = "select " & SelectedColumn & " from " & Table & " where " & ConditionField & " = " & ConditionValue
cmd = New OleDbCommand(Query, con)
DR = cmd.ExecuteReader
While DR.Read
FieldValue = DR.Item(SelectedColumn)
End While
End Sub

I create this sub to get one value to the database my database is Access 2010. When I run it the FieldValue is not returning the right value

Dim S As Integer
GetData("Price", "ProductList", "ProductName", "'7up'", S)

Now I use the Sub and print the value that it get, but the MsgBox value is zero(0). it should be Eight(8). I try to put a msgBox in Sub and Print FieldVAlue after it gets the value and it printing the correct value. But why my dim "S" is still zero? By the way the Sub is in my Module

Answer Source

Your problem is that FieldValue is a copy of S. You really not setting S at all. Declare ByRef FieldValue... and you in business

In there are value and reference types. Value type parameters, such as integer are passed as copy of value. While reference types passing copy of address. When you passed int (10) ByVal, you passed copy. When you do FieldValue = DR.Item(SelectedColumn), you set value inside your method. But you are not setting S. But if you pass it ByRef, you pass copy of address and in this case you set same value as S.

Of course, if you use while on the query that may return more then 1 result - it is a problem. At least, use if if you expect 1 value, or better yet - ExecuteScalar

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download