6

I creating multiline TextBox with this Link its work better but if I want to set TextBox text counter

label1.Content = textBox1.Text.Length;

with above line work fine but problem is that when I press enter in the TextBox counter it will increase 2 characters in TextBox counter.

How can I do this task please help me.

Any help appreciated!

Community
  • 1
  • 1
Jay Shukla
  • 782
  • 1
  • 13
  • 24

4 Answers4

6

Andrey Gordeev's answer is right (+1 for him) but does not provide a direct solution for your problem. If you check the textBox1.Text string with the debugger you would see the referred \r\n characters. On the other hand, if you intend to affect them directly (via .Replace, for example), you wouldn't get anything.

Thus, the practical answer to your question is: rely on Environment.NewLine. Sample code:

label1.Content = textBox1.Text.Replace(Environment.NewLine, "").Length;
varocarbas
  • 12,354
  • 4
  • 26
  • 37
3

That's because newline is presented by two symbols: \r and \n

Related question: What is the difference between \r and \n?

Community
  • 1
  • 1
Andrey Gordeev
  • 30,606
  • 13
  • 135
  • 162
3

if you need just one character on "Enter" then you can just handle PreviewKeyDown event on TextBox and paste following handler:

    private void Txt_OnPreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            var txtBox = e.Source as TextBox;
            var selectionStart = txtBox.SelectionStart;
            txtBox.Text = txtBox.Text.Insert(selectionStart, "\n");
            txtBox.Select(selectionStart + 1, 0);
            e.Handled = true;  
        }
    }
vitaliy zadorozhnyy
  • 1,226
  • 10
  • 12
  • Just as a comment. There is no special reason to use "\n" intead of Environment.NewLine. Actually, "\n" is "ignored" by most of the string analysing methods. Apparently, the OP likes your answer, even though he cannot get what he is after by relying on "\n" (counting the number of characters in a string without considering new line ones); he should rely on Environment.NewLine. I think that these ideas should be let clear for future readers. – varocarbas Aug 27 '13 at 09:20
  • 1
    I am every second more confused: I have tested your code and does not work at all. What is logical, on the other hand: as said you cannot affect the /n characters via string management method (what you are doing in the texbox). In case of being able to do that, the "enter effect"/new line would have disappeaedr, what is not what the OP wants, anyway ?! This is way too weird, for me. Ah! You have got a new +1 after my explanations!? Hmmm Impressive! LOL. – varocarbas Aug 27 '13 at 09:34
0

Use the code below instead of label1.Content = textBox1.Text.Length;

label1.Text = textBox1.Text.Replace(Environment.NewLine, "").Length.ToString();

Please don't forget to add using System.Text;

RohrerF
  • 33
  • 1
  • 10