Search code examples
c#winformstextboxinherited

Inherited TextBox missing CaretIndex property


I have the following code:

public class myTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);
        if (Char.IsDigit(e.KeyChar))  // Digits are OK
        {
            // execpt if cursor is at right end
            if (this.CaretIndex == this.Text.Length)
            {
                e.Handled = true;    // throw away keypress
            }
        }
    }
}

and I get the error:

'MyTextBoxes.myTextBox' does not contain a definition for 'CaretIndex' and no extension method 'CaretIndex'...

even though CaretIndex is a TextBox property: http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.caretindex(v=vs.110).aspx


Solution

  • Changed this line:

    if (this.CaretIndex == this.Text.Length)
    

    to this:

    if ((this.Text.Length > 0) && ((this.SelectionStart + this.SelectionLength) == this.Text.Length))