Reputation: 13
I develop c# windows form ModbusTCP Slave application which provides data from dataGridView. I create method which reading data from dataGridView and start listen. I need that I can refresh data in current listening.
My method:
void Button1Click(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();}
I need refresh data in DataGridView. How I can it? So, if I change data in table and click button again then I get an error. Thank you for your help
Upvotes: 1
Views: 4123
Reputation: 12355
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:
timer1
in the lower part of designer windowtimer1
. Visual Studio creates an handler for click event of your timer (it should be called timer1_Tick()
). The timer will periodically run the code you put in timer1_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.
Upvotes: 1