문제

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

도움이 되었습니까?

해결책

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:

  1. 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
  2. Double click on timer1. 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.
  3. 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();
    }
    
  4. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top