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