How to add a line to a multiline TextBox?

后端 未结 10 637
情话喂你
情话喂你 2020-12-01 15:32

How can i add a line of text to a multi-line TextBox?

e.g. pseudocode;

textBox1.Clear();
textBox1.Lines.Add(\"1000+\");
textBox1.Lines.Add(\"750-999\         


        
10条回答
  •  我在风中等你
    2020-12-01 16:20

    The "Lines" property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[], like you can to a List. There is simply no method available for the purpose. You must instead create a new string[] based on the current Lines reference, and assign it to Lines.

    Using a little Linq (.NET 3.5 or later):

    textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();
    

    This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you're setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you're set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:

    var myLines = new List();
    
    myLines.Add("brown");
    myLines.Add("brwn");
    myLines.Add("brn");
    myLines.Add("brow");
    myLines.Add("br");
    myLines.Add("brw");
    ...
    
    textBox1.Lines = myLines.ToArray();
    

    Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.

提交回复
热议问题