You can use a timer
object (more info here). For example you can start your timer pressing a button and then the timer can read data and update your gridview.
As an example you can follow these steps:
- Drag timer object from your Toolbox on your form (it should be in the "All Windows Forms" folder). Visual studio should create an object called
timer1
in the lower part of designer window - Double click on
timer1
. Visual Studio creates an handler for click event of your timer (it should be calledtimer1_Tick()
). The timer will periodically run the code you put intimer1_Tick()
event handler. Copy the code you wrote for your button in
timer1_Tick()
private void timer1_Tick(object sender, EventArgs e) { IPAddress address = IPAddress.Parse(tbIP.Text); int port = Convert.ToInt32(tbPort.Text); slaveTcpListener = new TcpListener(address, port); slave = ModbusTcpSlave.CreateTcp(1, slaveTcpListener); DataStore data = new DataStore(); for (int i=0; i<dgV.Rows.Count-1; i++) { slave.DataStore.InputRegisters[Convert.ToInt32(dgV[0,i].Value)] = (ushort)Convert.ToUInt16(dgV[1,i].Value); } slave.Listen(); }
Finally you have to configure and start your timer, for example with a button:
void Button1Click(object sender, EventArgs e) { timer1.Interval = 10000; //timer tick occurs every 10'000ms=10sec timer1.Enabled = true; timer1.Start(); }
Now if you click Button1
your timer starts and should read data from Modbus and update yor GridView
every 10 seconds.