I have textbox that I use for diagnostic purposes. The code behind is really simple:
XAML:
<TextBox HorizontalAlignment="Left" Margin="640,20,0,0" TextWrapping="Wrap" Height="280" Width="840" Name="txtDiagnostic" IsHitTestVisible="True" />
C#:
private void AddMessage(string message)
{
txtDiagnostic.Text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + message);
}
How can I define that each new input is on a different line? Because right now all errors are in just 1 long line.
14:15:00 Error 1 14:16:00 Error 2 14:17:00 Error 3
Instead of readable with line breaks between each error like this example:
14:15:00 Error 1
14:16:00 Error 2
14:17:00 Error 3
add an Environment.NewLine at the end of each string
txtDiagnostic.Text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + message) + Environment.NewLine;
and make sure that the textbox is capable of multiline
XAML:
<TextBox
Name="tbMultiLine"
TextWrapping="Wrap"
AcceptsReturn="True" <-- IMPORTANT
VerticalScrollBarVisibility="Visible" <-- IMPORTANT
>
EDIT: As to respond to the usual string concatination debate you can of course use string.Concat()
String.Concat(txtDiagnostic.Text,DateTime.Now.ToString("hh:mm:ss:fff") , " " , "ERROR....." , Environment.NewLine);
It will be faster. Here is a benchmark code for LINQPad with a 1000 lines:
void Main()
{
Stopwatch sw = new Stopwatch();
string text = "";
sw.Start();
for (int i = 0; i < 1000; i++)
{
//text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + "ERROR.....") + Environment.NewLine;
String.Concat(text,DateTime.Now.ToString("hh:mm:ss:fff") , " " , "ERROR....." , Environment.NewLine);
}
sw.Stop();
Console.WriteLine("ELAPSED: " + sw.ElapsedMilliseconds);
}
Output:
+
concatentation took (on my machine) 16 msek
Concat
needed 10 msek
Choose yourself, you should know how many error messages you would like to "inform" the user with ;)
Disclaimer: 1000 lines is a very bad benchmark, but I chose it here to fit the use case at hand. Reading more than a 1000 (or even a 1000) lines of error messages is not a software I would like to use. If you start concatenating larger sets of lines (x > 1000) then you really should use the StringBuilder
as is also mentioned in the string concatenation debate Link that I provided.