如何从串口直接接收串行通信数据到Gridview是可能的吗?

时间:2016-03-24 13:19:14

标签: c# winforms datagridview serial-port

是否可以通过c#windows窗体从串口接收数据到DataGridView。

到目前为止,我可以在文本框中看到数据,但我想在列中查看DataGridView中的所有数据,然后处理数据(进行计算和逻辑运算)。有没有办法从串口直接接收数据到gridview(不是文本框或外部数据源)

到目前为止,这是我的代码:Image of current data in text box

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 using System.Windows.Forms;
using System.IO.Ports;
namespace bandymas
{
public partial class Form1 : Form
{
    private SerialPort myport;
    private DateTime datetime;
    private string in_data;
    public Form1()
    {
        InitializeComponent();
    }
    private void start_btn_Click(object sender, EventArgs e)
    {
        myport = new SerialPort();
        myport.BaudRate = 9600;
        myport.PortName = port_name_tb.Text;
        myport.Parity = Parity.None;
        myport.DataBits = 8;
        myport.StopBits = StopBits.One;
        myport.DataReceived += Myport_DataReceived;
        try
        {
            myport.Open();
            data_tb.Text = "";
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }
    }
    void Myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        in_data = myport.ReadLine();
        this.Invoke(new EventHandler(displaydata_event));

    }
    private void displaydata_event(object sender, EventArgs e)
    {
        datetime = DateTime.Now;
        string time = datetime.Minute + ":" + datetime.Second + ":" +
                      datetime.Millisecond;
        data_tb.AppendText(time + " \t  " + in_data + "\n");
    }

    private void data_tb_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }
}

}

有新的工作代码:

  private void SerialPort1_DataReceived(object sender,  SerialDataReceivedEventArgs e)
    {
       in_data = serialPort1.ReadLine();
       this.Invoke(new EventHandler(displaydata_event));
      }
    private void displaydata_event(object sender, EventArgs e)
    {
        datetime = DateTime.Now;
        string time = datetime.Minute + "" + datetime.Second + "" +      datetime.Millisecond;
                   string str = in_data;
                   string aa = str.Substring(0, str.IndexOf(' '));
                   string bb = str.Substring(str.IndexOf(' ') +1 , str.LastIndexOf(' ') - str.IndexOf(' '));
        string cc = str.Substring(str.LastIndexOf(' ') + 1, str.Length -  str.LastIndexOf(' ') - 1);

        int ai = Convert.ToInt32(aa);
        int bi = Convert.ToInt32(bb);
        int ci = Convert.ToInt32(cc);

        dataGridView1.Rows.Add( ai , bi , ci  + "\n");

          }

0 个答案:

没有答案