2012-02-07 31 views
0

您好,我知道我的代碼是哪裏錯了,但不知道如何解決它......驗證文本框的文本,並增加標籤指數一度

上TextChanged事件,我把我的驗證功能,不(應該做的事)以下:

  • 刪除任何非字母字符
  • 輸入的字母轉換爲大寫
  • 只允許在文本框中一個字符
  • 使用到的SendKeys增加標籤索引(轉到下一個文本框)

問題是因爲它在textchanged事件中,我試圖與它作鬥爭以防止它兩次掛鉤(它正在這樣做)。因爲如果我通過,輸入的第一個字母是第一個textchanged事件,那麼如果它是一個不允許的字符,函數會再次被調用,但如果它是一個字母,ToUpper可能會再次更改它,因此選項卡會發送兩次。有任何想法嗎?我知道有辦法做到這一點,而不必設置一些複雜的bool ....

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

而不是使用的SendKeys模擬TAB按鍵,可以發現在標籤順序下一個可見的控制,並呼籲關注它。事情是這樣的:

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

要調用此方法,以FocusOnNextVisibleControl(T);

+0

我想這再更換SendKeys.Send("{TAB}");,我不知道如何下一個文本框的引用名。你會從函數中看到我正在接收發件人作爲文本框並將其引用爲控件。所以如果第一個文本框是'textbox1',我不知道如何使用我當前的設置將焦點更改爲'textbox2'。 – ikathegreat 2012-02-07 05:57:21

+1

我已經編輯了我的答案,以顯示如何將注意力集中在窗體的Tab鍵順序中的下一個控件上,而無需知道提前哪個控件。請注意,如果您在表單上有組框或其他容器控件,則可能需要更改上述代碼才能將其考慮在內。 – 2012-02-07 06:51:01

+0

muahahaha完美的作品,謝謝!回到工作.... – ikathegreat 2012-02-08 02:33:41