I'm doing a chat client, and currently I have a button that will display data to a multi-line textbox when clicked. Is this the only way to add data to the multi-line textbox? I feel this is extremely inefficient, because if the conversation gets really long the string will get really long as well.
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.Text += sent + "\r\n";
}
If you use WinForms:
Use the AppendText(myTxt)
method on the TextBox
instead (.net 3.5+):
private void button1_Click(object sender, EventArgs e)
{
string sent = chatBox.Text;
displayBox.AppendText(sent);
displayBox.AppendText(Environment.NewLine);
}
Text in itself has typically a low memory footprint (you can say a lot within f.ex. 10kb which is "nothing"). The TextBox does not render all text that is in the buffer, only the visible part so you don't need to worry too much about lag. The slower operations are inserting text. Appending text is relatively fast.
If you need a more complex handling of the content you can use StringBuilder
combined with the textbox. This will give you a very efficient way of handling text.
Because you haven't specified what front end (GUI technology) you're using it would be hard to make a specific recommendation. In WPF you could create a listbox and for each new line of chat add a new listboxitem to the end of the collection. This link provides some suggestions as to how you may achieve the same result in a winforms environment.
I find this method saves a lot of typing, and prevents a lot of typos.
string nl = "\r\n";
txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";
C# - serialData is ReceivedEventHandler
in TextBox
.
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
serialData.Invoke(new Action(() => serialData.Text = String.Concat(recvData)));
Now Visual Studio drops my lines. TextBox, of course, had all the correct options on.
Serial:
Serial.print(rnd);
Serial.( '\n' ); //carriage return