-
-
Save dj1711572002/33853cb363f159febab9ed6af6e0075c to your computer and use it in GitHub Desktop.
C# SerialTest DataGridView Reciving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
using System.Diagnostics; | |
namespace SerialTest | |
{ | |
public partial class Form1 : Form | |
{ | |
int j, rN; | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
serialPort1.BaudRate = 115200; | |
serialPort1.Parity = Parity.None; | |
serialPort1.DataBits = 8; | |
serialPort1.StopBits = StopBits.One; | |
serialPort1.Handshake = Handshake.None; | |
serialPort1.PortName = portComboBox.Text; | |
serialPort1.Open(); | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
string[] ports = SerialPort.GetPortNames(); | |
foreach (string port in ports) | |
{ | |
portComboBox.Items.Add(port); | |
} | |
if (portComboBox.Items.Count > 0) | |
portComboBox.SelectedIndex = 0; | |
rN = 0; | |
} | |
private void button2_Click(object sender, EventArgs e) | |
{ | |
if (serialPort1.IsOpen) | |
{ | |
serialPort1.Write(textBox2.Text + "\n"); | |
} | |
} | |
delegate void SetTextCallback(string text); | |
private void Response(string text) | |
{ | |
if (textBox1.InvokeRequired) | |
{ | |
SetTextCallback d = new SetTextCallback(Response); | |
BeginInvoke(d, new object[] { text }); | |
} | |
else | |
{ | |
// textBox1.AppendText(text + "\n"); | |
//===============データグリッドビュー dgv1へ記録=================== | |
string[] data =( text+",\n").Split(',');//カンマ区切りにばらす | |
int cN = data.Length; | |
if (rN == 0)//行カウントrN==0のときdgv1定義 | |
{ | |
dgv1.ColumnCount = cN ; | |
dgv1.RowCount = 2; | |
dgv1.RowHeadersWidth = 100; | |
dgv1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;//CRLF | |
} | |
rN++; | |
dgv1. FirstDisplayedScrollingRowIndex = rN; | |
dgv1.Rows.Add(data); | |
dgv1.Rows[rN].HeaderCell.Value = rN.ToString(); | |
//================================================================= | |
} | |
} | |
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) | |
{ | |
string str = serialPort1.ReadLine(); | |
Response(str); | |
} | |
private void button3_Click(object sender, EventArgs e) | |
{ | |
serialPort1.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment