Smoky2016 Smoky2016 - 8 days ago 4
Vb.net Question

How do I convert an object from an external collection of items to an Integer type

How do I convert object data type to an integer?

I am trying to do a calculation on my application, reading the OPC item’s value. Objects are used to identify the OPC items within a server.

Here is what I am trying to do:

Itemvalues(0) * 1000 + itemvalues(1)

Itemvalues is the OPC item’s value.

Itemvalues is an object data type and it can contain any data type. But you have to convert it.

(*) is multiplication.

1000 is an integer

(+) is addition

Below is the code I tried:

Dim y As Object
Dim yR As Integer
Dim z As Object
Dim zR As Integer
Dim x = 1000

yR = CInt(y)
zR = CInt(z)

y = itemValues(1).Value
z = itemValues(2).Value
itemValues(1).Value = yR * x + zR


But it is displaying 0:

Which is the wrong calculation, and it is because the default value of Object is Nothing (a null reference).. How do I calculate this?

Answer

Your question is not entirely clear, but there is an obvious logic problem in your code.

You are assigning the values of yR and zR from the variables y and z before you are assigning anything to y and z. So these values will always be 0.

Swap the assignment order like this:

 y = itemValues(1).Value
 z = itemValues(2).Value 

yR = CInt(y)
zR = CInt(z)

There are other issues in your code but this is probably your immediate problem.