Manipulating TextBox

1

Simply fill in the fields Modelo , Placa , Km and this will be saved in the multiline fields below:

ButwhenIclickthe"Save" button, the result is completely opposite to what you expected. I wanted each field to be one ahead of the other and when it arrived at the end "novoCarro.mostraKm()" it would skip one line to save the next vehicle on the next line.

txtCarros.Text += novoCarro.mostraModelo() + "/t";

txtCarros.Text += novoCarro.mostraPlaca() + "/t";

txtCarros.Text += novoCarro.mostraKm() + "/r/n";
    
asked by anonymous 25.01.2018 / 20:04

3 answers

4

The best way to do this is:

txtCarros.Text = string.Join("\t", novoCarro.mostraModelo(), novoCarro.mostraPlaca(), novoCarro.mostraKm(), "\n");

Manually concatenating string generates several allocations and this, in addition to being slow, creates pressure on the garbage collector. This case does not do much damage, but if it increases the number of items it gets worse exponentially.

I put the tabs that is the question asks, and the line break only at the end.

Simplified:

public class Program { public static void Main() => System.Console.WriteLine(string.Join("\t", "modelo", "placa", "km", "\n")); }

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

Join() documentation.

But if you're doing everything in the same expression you can simplify the syntax that the compiler will transform to Concat() for you, and it fits even better:

txtCarros.Text = novoCarro.mostraModelo() + "\t" + novoCarro.mostraPlaca() + "\t" novoCarro.mostraKm() + "\n";

For a few items it does not make sense to use StringBuilder , especially when the final size is unknown.

Another alternative would be:

txtCarros.Text = $"{novoCarro.mostraModelo()}\t{novoCarro.mostraPlaca()}\t {novoCarro.mostraKm()}\n";
    
25.01.2018 / 21:33
2

To break string line, just replace the / t bar with a backslash "\ n"

txtCarros.Text += novoCarro.mostraModelo() + "\n";

txtCarros.Text += novoCarro.mostraPlaca() + "\n";

txtCarros.Text += novoCarro.mostraKm() + "\n";

Another way is to use String + Environment.NewLine + String.

    
25.01.2018 / 20:21
0

What is wrong with your code, in addition to manually concatenating strings, is to be using / instead of \ , as escape character. Instead of "/t" you should use "\t" and, for line break, "\n" .

To avoid the problems (slow and pressure on the garbage collector) of manual concatenation of strings and what shows you are doing use the #:

StringBuilder builder = new StringBuilder();
builder.Append(novoCarro.mostraModelo());
builder.Append("\t");
builder.Append(novoCarro.mostraPlaca());
builder.Append("\t");
builder.AppendLine(novoCarro.mostraKm());
txtCarros.Text = builder.ToString();
    
25.01.2018 / 21:49