white_reece white_reece - 2 years ago 88
C# Question

C# - Overwrite / Update text in TextBlock

I am currently building a WPF application that receives and displays data from an Arduino using a SerialPort connection. I have managed to get the live data to display as it is received, however when the text reaches the bottom of the TextBlock the text stops. I would like to replace the old values with the new data coming in. Is this possible?

This is my code

public partial class MainWindow : Window
SerialPort sp = new SerialPort();

public MainWindow()

private void btnCon_Click(object sender, RoutedEventArgs e)
String portname = txtCom.Text;
sp.PortName = portname;
sp.BaudRate = 9600;
sp.DtrEnable = true;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
txbStatus.Text = "Connected";
catch (Exception)
MessageBox.Show("Please enter a valid port number");

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
this.Dispatcher.Invoke(() =>
SerialPort sp = (SerialPort)sender;
txbStatus.Text += sp.ReadExisting(); //Displaying data in TextBlock


Answer Source

Just change

txbStatus.Text +=


txbStatus.Text =

EDIT in response to comment

You might want to use ReadLine instead, but make sure to set the newline character with SerialPort.NewLine. See also this question's replies.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download