OPC Data Client - OPC DA - Using State Object When Subscribing to a Tag
How do I reference the state object when subscribing to a tag?
Example code demonstrating how to bind a value to a form object using the State property in a subscription is shown below.
C#
private void StateObjectExample_ItemChanged(object sender, OpcLabs.EasyOpc.DataAccess.EasyDAItemChangedEventArgs e)
{
try
{
//reference the state object passed from the subscription call, send value to placeholder object
TextBox tb = (TextBox)e.State;
//set textbox.text to the tag's returned value
tb.Text = e.Vtq.Value.ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error {0}", ex.ToString());
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Create the client object
OpcLabs.EasyOpc.DataAccess.EasyDAClient StateObjectExample = new OpcLabs.EasyOpc.DataAccess.EasyDAClient();
//assign the callback event to the OPC Client object
StateObjectExample.ItemChanged += new System.EventHandler<OpcLabs.EasyOpc.DataAccess.EasyDAItemChangedEventArgs>(this.StateObjectExample_ItemChanged);
//Subscribe to the tag, and pass the State Object (there is a text box object on the form in this example)
StateObjectExample.SubscribeItem("127.0.0.1", "SWToolbox.TOPServer.V5", "Simulation Examples.Functions.User1", 100, textBox1);
}
VB.NET
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'
'Create an instance of the EasyDAClient object
Dim EasyDAClient As New OpcLabs.EasyOpc.DataAccess.EasyDAClient
'
'Add the event handler for the ItemChanged event
AddHandler EasyDAClient.ItemChanged, AddressOf EasyDAClient_ItemChanged
'
'Subscribe to the tag passing in: computer name, server name, tag name, scan rate,
'and state object (i.e. object you want to bind the value to)
EasyDAClient.SubscribeItem("", "SWToolbox.TOPServer.V5", "Channel1.Device1.Tag1", 1000, TextBox1)
End Sub
'
'This is the callback event for the subscription
Private Sub EasyDAClient_ItemChanged(sender As Object, e As OpcLabs.EasyOpc.DataAccess.EasyDAItemChangedEventArgs)
'set the returned value property of the vtq equal to the textbox property of the state object
'which in this example is a textbox on the form
e.State.Text = e.Vtq.Value.ToString
End Sub
End Class