January 2, 2007

Controlling TextBox Character Input

Good set opf samples
/// <summary>
/// Ensure only alpha numeric characters and
/// backspace are acceptable characters for the Thingey
/// </summary>
/// <param name="sender"></param>
/// <param name="kpea"></param>
private void OnSomeTextBox_KeyPressEvent(object sender, 
    KeyPressEventArgs kpea)
{
    const char BACKSPACE = '\b';
    const char FULLSTOP = '.';
    if (textBox.Text.Length > 0) // AFter first character
    {
        if ( !Char.IsLetterOrDigit(kpea.KeyChar) && 
            (kpea.KeyChar != BACKSPACE) && 
            (kpea.KeyChar != FULLSTOP))
        { // input is not passed on to the control(TextBox)
            kpea.Handled = true; 
        }
    } // First character must be an alphabetic character
    else if (!Char.IsLetter(kpea.KeyChar)) 
    {
 // input is not passed on to the control(TextBox)
        kpea.Handled = true; 
    }
}

// Another example
    switch(kpea.KeyChar) 
    {  
        case 'a': 
        case 'b': 
        case 'c': 
        case '#': 
        case '*': 
        case '1': 
            e.Handled=true; //event is handled.
            this.errorProvider.SetError(this.textboxChars, 
               "not allowed chars: 'a','b','c','#','*','1'");
            this.statusBar.Text="not allowed char..."+e.KeyChar;
            break; 
       default:
            //clear error
            this.errorProvider.SetError(this.textboxChars, "");
            break;
    } //switch 


    private static class FilterCharacters
    {
        public static void FilterSample(TextBox tb, 
     KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            const char FULLSTOP = '.';
            const char HYPHEN = '-';
            const char UNDERSCORE = '_';
            if (tb.Text.Length > 0)
            {
                if (!Char.IsLetterOrDigit(kpea.KeyChar) && 
                    (kpea.KeyChar != BACKSPACE) && 
                    (kpea.KeyChar != FULLSTOP) &&
                    (kpea.KeyChar != HYPHEN) &&
                    (kpea.KeyChar != UNDERSCORE) )
                { // input is not passed on to the control(TextBox)
                    kpea.Handled = true; 
                }
            }// First character must be an alphabetic character
            else if (!Char.IsLetter(kpea.KeyChar)) 
            {// input is not passed on to the control(TextBox)
                kpea.Handled = true; 
            }
        }

        public static void NumericOnlyFilter(TextBox tb,
      KeyPressEventArgs kpea)
        {
            const char BACKSPACE = '\b';
            //const char FULLSTOP = '.';
            if (!Char.IsDigit(kpea.KeyChar) && 
                // If you want decimal numbers
                //(kpea.KeyChar != FULLSTOP) && 
                (kpea.KeyChar != BACKSPACE) ) 
            {
               kpea.Handled = true; 
            }
        }
    }

No comments: