validate textbox text and increase the tab index once

…衆ロ難τιáo~ 提交于 2019-12-25 01:17:09

问题


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}");
            }
        }

回答1:


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);



来源:https://stackoverflow.com/questions/9171452/validate-textbox-text-and-increase-the-tab-index-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!