Adding new line of data to TextBox

前端 未结 5 1311
一生所求
一生所求 2020-12-08 13:31

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 textb

相关标签:
5条回答
  • 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.

    0 讨论(0)
  • 2020-12-08 13:51

    Following are the ways

    1. From the code (the way you have mentioned) ->

      displayBox.Text += sent + "\r\n";
      

      or

      displayBox.Text += sent + Environment.NewLine;
      
    2. From the UI
      a) WPF

      Set 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
      
    0 讨论(0)
  • 2020-12-08 13:57

    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
    
    0 讨论(0)
  • 2020-12-08 13:58

    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.

    0 讨论(0)
  • 2020-12-08 14:00

    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";

    0 讨论(0)
提交回复
热议问题