Friday, February 3, 2012

[Csharp] Tip/Trick to select text in TextBox

Today, I write an application to load long text document on TextBox. Working with long text, so I need to create some alternative functions such as: search text, go to line. All function is around how to select text on TextBox. Here is some code snippet to do it:

* Search on textbox: keyword is your input


   1:                  textBox.Focus();                
   2:                  textBox.SelectionStart = index;
   3:                  textBox.SelectionLength = keyword.Length;
   4:                  textBox.ScrollToCaret();

 * Go to line: lineToGo is your input


   1:              textBox.Focus();
   2:              textBox.SelectionLength = 0;
   3:              textBox.SelectionStart = textBox.GetFirstCharIndexFromLine(lineToGo);
   4:              textBox.ScrollToCaret();

* Select all and copy text


   1:              textBox.Focus();
   2:              textBox.SelectAll();
   3:   
   4:              if (string.IsNullOrEmpty(textBox.SelectedText)) return;
   5:              Clipboard.SetText(textBox.SelectedText);
   6:              textBox.Focus();
OK, I think it's so easy and we will meet it many times in code.
Thank to enjoy!

*Update:
Get number of lines of selected text


   1:          private static int GetSelectedLines(TextBox textBox)
   2:          {
   3:              if (textBox.SelectionLength == 0) return 0;
   4:   
   5:              return textBox.GetLineFromCharIndex(textBox.GetFirstCharIndexOfCurrentLine()) -
   6:                     textBox.GetLineFromCharIndex(textBox.SelectionStart);
   7:          }
:)

No comments:

Post a Comment