3

Is any way to receive data from serial port to DataGridView in c# windows forms.

Up to now I can see data in text box but I want to see all data in DataGridView in columns and then process data (make calculations and logical operations). Is any way to receive data from serial port straight to gridview (not text box or external data source)

This is my code up to now: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)
    {

    }
}

}

There is new working code:

  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");

          }
  • 1
    __Do not__ call a `DataGridView`a `GridView`!! This is wrong and confusing.. Always call things by their __right__ name! Yes, it takes __four__ letters more to type.. – TaW Mar 24 '16 at 13:27
  • @TaW, why wrong and confusing? `using System.Windows.Forms` is pretty clearly says `winforms` as for me. You mean wrong tag? Or another component (I think there was one in past), but then `DataGridViewCellEventArgs` makes it clear too. – Sinatr Mar 24 '16 at 13:29
  • Why wrong? Because it is. Why confusing? Because the tag system doesn't work with wrong terms. Do you know haw many questions __lazily__ tagged `GridView` get `WPF` answers wasting everybody's time?! As for the title: I never ought to have `Winforms` (or for that matter `c#`) in the title but in the tag etc.. – TaW Mar 24 '16 at 13:31
  • Even professors sometimes call things wrongly. I wouldn't expect from beginner (guessing from difficulty of the problem) to use right terminology. And even professionals can't decide is it "to rise event" (microsoft recommends) or "to fire" it or "to call", etc. ;) – Sinatr Mar 24 '16 at 13:35
  • Sure. I simply told him to use the correct terms. I didn't downvote him or call him names ;-) The compiler will not be as forgiving as you are.. – TaW Mar 24 '16 at 13:36
  • Do you want to add 1 row or 1 column per data record? – TaW Mar 24 '16 at 13:39
  • I advise against calling `ReadLine` in `DataReceived`. `ReadLine` may block until the line is read. `DataReceived` is meant to handle data present *so far* without blocking. I suggest you append the result of `ReadToEnd` to a `StringBuilder` and check that for the completion of a line. – Thorsten Dittmar Mar 24 '16 at 14:14
  • I'm using rotatory encoder and Arduino board. From there serial port getting time and rotation count as you can see in picture. I just need all this data to be in grid view instead of text box. So that would be time in one column and rotations in another column.So that will add 1 row in both columns per data record. Data is sent every 33 microseconds. So then I can work out with formulas speed, direction and so on, and display results of action. For now I'm using excel but I need stand alone application so that's way I'm trying to create app which counts all things like excel does. – Raimondas Lukosius Mar 25 '16 at 14:16
  • My question is not duplicated please don't confuse. In link provided at the top of this page is HOW TO ADD ROW'S AND COLUMNS TO GRIDVIEW. – Raimondas Lukosius Mar 25 '16 at 18:00
  • My question is how to receive serial communication data from serial port straight to Gridview columns – Raimondas Lukosius Mar 25 '16 at 18:01
  • I did tried to replace text box with grid vew but no luck. – Raimondas Lukosius Mar 25 '16 at 18:12
  • there is link to my files: https://onedrive.live.com/redir?resid=4E34642B363133F3!1341&authkey=!AFJjZZfmurfVBSU&ithint=file%2crar so you can use to if you need something similar. You can connect to port and read + save data to file(just change path in code for your folder path). All data goes to text box and from there you can save to excel. My goal is to replace text bog with grid view but still don't know how to do it. :) – Raimondas Lukosius Mar 26 '16 at 00:36
  • I managed to do it :) – Raimondas Lukosius Apr 26 '16 at 19:58

0 Answers0