Вопрос

hi i know where my code is going wrong, but don't know how to fix it...

on the TextChanged event, i call my validation function which does (is supposed to do) the following:

  • remove any non letter character
  • convert the entered letter to upper case
  • only allow one character in the textbox
  • use SendKeys to increase the tab index (go to next textbox)

problem is since it is in the textchanged event, i'm trying to fight it to prevent it from tabbing twice (which it is doing). because the if i step through, the initial letter entered is the first textchanged event, then if it is a notallowedcharacter, the function is called again, but if it is a letter, the ToUpper may be changing it again so tab is getting sent twice. any ideas? i know there's a way to do this without setting up some complex bools....

private void validateTextInteger(object sender, EventArgs e)
        {
            TextBox T = (TextBox)sender;
            try
            {
                //Not Allowing Numbers, Underscore or Hash
                char[] UnallowedCharacters = { '0', '1','2', '3', '4', '5','6', '7','8', '9','_','#','%','$','@','!','&',
                                           '(',')','{','}','[',']',':','<','>','?','/','=','-','+','\\','|','`','~',';'};

                if (textContainsUnallowedCharacter(T.Text, UnallowedCharacters))
                {
                    int CursorIndex = T.SelectionStart - 1;
                    T.Text = T.Text.Remove(CursorIndex, 1);
                    //Align Cursor to same index
                    T.SelectionStart = CursorIndex;
                    T.SelectionLength = 0;
                }
            }
            catch (Exception) { }
            T.Text = T.Text.ToUpper();
            if (T.Text.Length > 0)
            {
                 //how do i prevent this (or this function) from getting called twice???
                 SendKeys.Send("{TAB}");
            }
        }
Это было полезно?

Решение

Instead of using SendKeys to simulate a TAB keypress, you can find the next visible control in the tab order and call Focus on it. Something like this:

private void FocusOnNextVisibleControl(Control currentControl)
{
    Form form = currentControl.FindForm();
    Control nextControl = form.GetNextControl(currentControl, true);
    while (nextControl != null && !nextControl.Visible && nextControl != currentControl)
    {
        nextControl = form.GetNextControl(nextControl, true);
    }
    if (nextControl != null && nextControl.Visible)
    {
        nextControl.Focus();
    }
}

To call this method, replace SendKeys.Send("{TAB}"); with FocusOnNextVisibleControl(T);

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top