'Adding new line of data to TextBox
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";
}
Solution 1:[1]
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPFSet TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
Solution 2:[2]
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";
Solution 3:[3]
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.
Solution 4:[4]
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
Solution 5:[5]
I use this function to keep newest at top:
WriteLog("hello1");
WriteLog("hello2");
WriteLog("hello3");
public void WriteLog(string text)
{
var last = txtLog.Text;
txtLog.Text = DateTime.Now.ToString("G") + ": " + text;
txtLog.AppendText(Environment.NewLine);
txtLog.AppendText(last);
}
Will output this:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tilak |
Solution 2 | DanKuz |
Solution 3 | alan |
Solution 4 | Acapulco |
Solution 5 | kuhi |