6 Replies - 5648 Views - Last Post: 28 October 2014 - 05:26 AM Rate Topic: -----

#1 rikiz   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 28-October 14

How to update text in WinForms Textbox?

Posted 28 October 2014 - 02:14 AM

I am trying to create an application interface serial data reception using c #.
I send the data from the serial adc microcontroller adc atmega 16 ... the data is 0 to 1023.
in the textbox that I use as a data reception, data updates to the bottom if I use ReadLine coding.
examples:
1023
1023
1023
256
669


if I use ReadExisting, the data displayed by the textbox moves to the side. examples 102310231023256669
I wanted
when the data changes from 0-1023 of serial communication, and clear the data will store in otomatiis in the textbox.
instance
when there is reception of data with a value of 1023 and immediately there is a change to the value of 555
textbox value will not store the value of 1023, I want the value in 1023 immediately deleted automatically and change the value to 555 when a change in the value of the data ...
The following is the complete source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 

namespace serial
{
public partial class Form1 : Form
{
Double arus, tegangan;
public Form1()
{
InitializeComponent();
}
 
// Source program komunikasi serial
 
private void Form1_Load(object sender, EventArgs e)
{
//—menset event handler untuk DataReceived event—
serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceived);
//—menampilkan nama serialport yang tersedia pada
// komputer—
string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
for (int i = 0; i <= portNames.Length - 1; i++)
{
cbbCOMPorts.Items.Add(portNames[i]);
}
btnDisconnect.Enabled = false;
}
 
private void btnConnect_Click(object sender, EventArgs e)
{
//—menutup akses serialport apabila akses serialport terbuka—
if (serialPort.IsOpen)
{
serialPort.Close();
}
try
{
//—mengatur beberapa parameter untuk koneksi serial
// port—
serialPort.PortName = cbbCOMPorts.Text;
serialPort.BaudRate = 9600;
serialPort.Parity = System.IO.Ports.Parity.None;
serialPort.DataBits = 8;
serialPort.StopBits = System.IO.Ports.StopBits.One;
//—buka serial port—
serialPort.Open();
//—menampilkan status dari serial port dan
// enable/disable -kan tombol—
lblMessage.Text = cbbCOMPorts.Text + " connected.";
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
 
private void btnDisconnect_Click(object sender, EventArgs e)
{
try
{
//—tutup serial port—
serialPort.Close();
//—menampilkan status dari serial port dan
// enable/disable -kan tombol—
lblMessage.Text = serialPort.PortName +" disconnected.";
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
 

private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//—memanggil delegasi untuk mengambil data yang diterima—
txtDataReceived.BeginInvoke(new myDelegate(updateTextBox));
}

//—Delegate and subroutine untuk ditampilkan pada TextBox control—
public delegate void myDelegate();
public void updateTextBox()
{
//—menambahkan data pada TextBox control—
txtDataReceived.AppendText(serialPort.ReadLine());
txtDataReceived.ScrollToCaret();




}
 
string aku;
private void textBox3_TextChanged(object sender, EventArgs e)
{
aku = Convert.ToString(txtDataReceived);

 
}
 
private void cbbCOMPorts_SelectedIndexChanged(object sender, EventArgs e)
{
 
}

This post has been edited by tlhIn`toq: 28 October 2014 - 03:14 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How to update text in WinForms Textbox?

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 03:30 AM

I cleaned up the code for the rest of us:

using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace WinFormsSerial
{
	// Source program komunikasi serial
	public partial class Form1 : Form
	{
		#region Delegates

		public delegate void myDelegate();

		#endregion

		#region Fields
		private string aku;
		private Double arus, tegangan;
		#endregion

		public Form1()
		{
			InitializeComponent();
		}

		public void updateTextBox()
		{
			//—menambahkan data pada TextBox control—
			txtDataReceived.AppendText(serialPort.ReadLine());
			txtDataReceived.ScrollToCaret();
		}

		private void DataReceived(object sender, SerialDataReceivedEventArgs e)
		{
			//—memanggil delegasi untuk mengambil data yang diterima—
			txtDataReceived.BeginInvoke(new myDelegate(updateTextBox));
		}


		private void Form1_Load(object sender, EventArgs e)
		{
			//—menset event handler untuk DataReceived event—
			serialPort.DataReceived += DataReceived;
			//—menampilkan nama serialport yang tersedia pada
			// komputer—
			string[] portNames = SerialPort.GetPortNames();
			for (int i = 0; i <= portNames.Length - 1; i++)
			{
				cbbCOMPorts.Items.Add(portNames[i]);
			}
			btnDisconnect.Enabled = false;
		}

		private void btnConnect_Click(object sender, EventArgs e)
		{
			//—menutup akses serialport apabila akses serialport terbuka—
			if (serialPort.IsOpen)
			{
				serialPort.Close();
			}
			try
			{
				//—mengatur beberapa parameter untuk koneksi serial
				// port—
				serialPort.PortName = cbbCOMPorts.Text;
				serialPort.BaudRate = 9600;
				serialPort.Parity = Parity.None;
				serialPort.DataBits = 8;
				serialPort.StopBits = StopBits.One;
				//—buka serial port—
				serialPort.Open();
				//—menampilkan status dari serial port dan
				// enable/disable -kan tombol—
				lblMessage.Text = cbbCOMPorts.Text + " connected.";
				btnConnect.Enabled = false;
				btnDisconnect.Enabled = true;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}

		private void btnDisconnect_Click(object sender, EventArgs e)
		{
			try
			{
				//—tutup serial port—
				serialPort.Close();
				//—menampilkan status dari serial port dan
				// enable/disable -kan tombol—
				lblMessage.Text = serialPort.PortName + " disconnected.";
				btnConnect.Enabled = true;
				btnDisconnect.Enabled = false;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
			}
		}


		private void cbbCOMPorts_SelectedIndexChanged(object sender, EventArgs e)
		{
		}

		private void textBox3_TextChanged(object sender, EventArgs e)
		{
			aku = Convert.ToString(txtDataReceived);
		}
	}
}

Was This Post Helpful? 1
  • +
  • -

#3 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 03:38 AM

Quote

I want the value in 1023 immediately deleted automatically and change the value to 555 when a change in the value of the data ...


Then don't append to the text already in the textbox

Quote

txtDataReceived.AppendText(serialPort.ReadLine());


Instead just set the text to the new value

		public void updateTextBox()
		{
			//—menambahkan data pada TextBox control—
			string newValue = serialPort.ReadLine();
			txtDataReceived.Text = DateTime.Now.ToString("HH:mm:ss.fff> " + newValue);
			txtDataReceived.ScrollToCaret();
		}


Was This Post Helpful? 1
  • +
  • -

#4 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 03:58 AM

See FAQ # 15 below for a link to a tutorial on how to use the serial port.

TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 6: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated July 2014
Spoiler

Was This Post Helpful? 1
  • +
  • -

#5 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 05:19 AM


Looking at your code you have some bad practices in play that need your immediate attention.
These will form bad habits quickly and should be worked on. This is part of what I mean by "learn foundation concepts first".

Problem 1: Use of GUI controls as your variables.
You have numerous places where you are doing things like: SomeMethodCall(TextBox43.Text);
Your textboxes and other GUI elements are not meant to be your variables to hold values. They exist only to be a way for the user to interact with the data held in the logic code *behind* the GUI. You should have properties bound to the GUI. When the user changes something in a textbox it updates the property in your code. When the property gets a new value, the GUI is updated. But your logic always uses the property not the GUI element.
There is a tutorial on properties linked in my signature block.

Problem 2: This bit about button1 and textbox14 is just horrible. If you are working in old 1980's WinForms for Win98 and WinXP programs then name your control as soon as you make it before doing anything else with it. txtbxFirstName is so much easier to maintain than textbox32. Same with "frmConnectionSettings" instead of "form2" or "wndCustomerDetails" than "window4". If you are making programs for current OSes like Win7/8 then you should be working in WPF where the controls don't need to be named 90% of the time, but the same practice of giving meaningful names should still be followed in the few cases where they are needed.

Problem 3: Don't put meaningful operational code in GUI control handlers. You have a lot of places where the work is being done in the button event handler instead if in a dedicated method. Instead you want that handler to just direct action to the first methods, not actually perform the actions.
btnSave_Click(object sender, eventargs e)
{
   SaveSettings(); // Call the save method
   SavePlayers();
   SaveWindowGeometry();
   // Do NOT put all the save code here
}

This way you can call the same save methods independently form code without having to either duplicate code (evil practice) or without calling the button handler. If you are using WinForms then you have a .Click event handler. If you are writting in WPF then don't call the .Click event but instead create Commands and activate those. The .Click handler in WPF is kind of a carry-over to give WinForms coders a comfortable migration path but is not considered the way a modern profession WPF coder works.

Problem 4:
Eye sore code.
Take the extra 2 minutes to clean up your code to make it easy to read, easy to follow, and most important, easy to manage.
  • Kill all those dead blank lines at the ends of methods.
  • Wrap groups of methods that go together in #region blocks so you can find all your sending code and receiving code easily for example.
  • Get your lines aligned. Control-K, Control-D will do that for you (Think of it as Klean Document)


Problem 5: Decent naming
Methods like private void ClientSession(object sender, eventargs e); don't follow established naming style guides.
A method performs an action. By convention for decades methods are named as verbs to show what they do. Nouns like ClientSession would be presumed to be a property by any other coder looking at your code. private void CreateClientSession(object sender, eventargs e); on the other hand shows that it does something (a method) not that it is something (a variable).

I'm not going to go into a long critique of your code. And I don't want you to feel like I'm just out to pick on you. I'm just pointing out a couple of many foundation concepts you didn't pickup up in the early stages of learning C#. You can't leap-frog the learning process by trying to build a program in your first month. Nobody can. Its not just you. Nobody in the first month of a new discipline has enough knowledge to jump in and start designing finished solutions: Not carpentry, not automotive design, not software engineering. C# is a foreign language with its own syntax. You aren't going to say "I know no Russian. I'm going to write a Russian mystery novel as my vehicle to learn the language." Same here with programming.

I urge you to take a step back. Pick up a "Learn C# in 30 days" type book and work your way through it cover to cover; don't use it a like a reference dictionary when you get stuck. There are several in a thread pinned to head of the C# forum. Plus there are countless C# beginner tutorial series around just like the C# Learning Series - tutorials here on DIC. There are also numerous "My First C# Program" tutorials like this one that will help you with the design and OOP concepts that are vital to good programming.

Was This Post Helpful? 0
  • +
  • -

#6 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15262
  • View blog
  • Posts: 61,186
  • Joined: 12-June 08

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 05:22 AM

Ah.. I thought the point of your whole FAQ system was so you did not need to paste things like post #5. :?:
Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: How to update text in WinForms Textbox?

Posted 28 October 2014 - 05:26 AM

#5 is more a set of common errors than answers to questions. Its a critique and set of suggestions so the only question it answers is the one rarely asked: "What do you think of my code?"
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1