Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# textbox cursor positioning

I feel like I am just missing a simple property, but can you set the cursor to the end of a line in a textbox?

private void txtNumbersOnly_KeyPress(object sender, KeyPressEventArgs e)
{
   if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == '.' || e.KeyChar == '-')
   {
      TextBox t = (TextBox)sender;
      bool bHandled = false;
      _sCurrentTemp += e.KeyChar;

      if (_sCurrentTemp.Length > 0 && e.KeyChar == '-')
      {
         // '-' only allowed as first char
         bHandled = true;
      }

      if (_sCurrentTemp.StartsWith(Convert.ToString('.')))
      {
         // add '0' in front of decimal point
         t.Text = string.Empty;
         t.Text = '0' + _sCurrentTemp;
         _sCurrentTemp = t.Text; 
         bHandled  = true;
      }

      e.Handled = bHandled;
   }

After testing for '.' as first char, the cursor goes before the text that is added. So instead of "0.123", the results are "1230." without moving the cursor myself.

I also apologize if this is a duplicate question.

like image 446
Jim Avatar asked May 04 '10 16:05

Jim


2 Answers

t.SelectionStart = t.Text.Length;
like image 97
Dean Kuga Avatar answered Oct 20 '22 23:10

Dean Kuga


in WPF you should use :

textBox.Select(textBox.Text.Length,0);

where 0 is the number of characters selected

like image 24
Rui Marques Avatar answered Oct 20 '22 22:10

Rui Marques