2013-04-10 77 views
1

我的表單中有一個文本框,用於鍵入項目代碼。 當文本框的焦點丟失時,它將查看數據庫以檢查項目代碼是否存在。 但是,當我嘗試通過單擊其他文本框失去焦點時,我正在無限循環。TextBox LostFocus無限循環

private void txtICode_LostFocus(object sender, RoutedEventArgs e) 
    { 
     if (txtICode.IsFocused != true) 
     { 
      if (NewData) 
      { 
       if (txtICode.Text != null) 
       { 
        if (txtICode.Text != "") 
        { 
         Item temp = new Item(); 
         Item[] list = temp.Query(new object[] { Item.DataEnum.Item_Code }, new string[] { txtICode.Text }); 
         if (list.Length > 0) 
         { 
          System.Windows.Forms.MessageBox.Show("This item code is already being used.", "Invalid information"); 
          txtICode.Focus(); 
          return; 
         } 
        } 
       } 
      } 
     } 
    } 

txtICode.IsFocused在方法結束後每次都設置爲true,並且循環只是持續下去。 我嘗試刪除txtICode.Focus();但它沒有區別。 我的代碼有什麼問題嗎?

我使用.Net 3.5和WPF爲我的表單。

+0

爲什麼恢復專注於'LostFocus'事件? – 2013-04-10 04:12:47

+0

刪除msgbox&check! – 2013-04-10 04:13:31

+0

即使在我註釋掉消息框之後,我仍然無限循環。我甚至註釋掉'txtICode.Focus()'部分。 – Digital 2013-04-10 04:18:30

回答

1

您不必在LostFocus事件中將焦點恢復到TextBox

刪除這兩條線:

txtICode.Focus(); 
return; 

您可以實現代碼更乾淨&可讀的方式:

private void txtICode_LostFocus(object sender, RoutedEventArgs e) 
{   
    if (!NewData) 
     return; 

    if (String.IsNullOrEmpty(txtICode.Text)) 
     return; 

    Item temp = new Item(); 
    Item[] list = temp.Query(new object[] { Item.DataEnum.Item_Code }, new string[] { txtICode.Text }); 
    if (list.Length > 0) 
    { 
     System.Windows.Forms.MessageBox.Show("This item code is already being used.", "Invalid information"); 
    } 
} 
+0

這個很好用!謝謝!代碼實際上是由其他人編寫的,我試圖修復一些錯誤並改進代碼。再次感謝! – Digital 2013-04-10 04:25:36

0

您可以使用BeginInvoke Method異步執行:

private void txtICode_LostFocus(object sender, RoutedEventArgs e) 
{ 
    txtICode.Dispatcher.BeginInvoke(() => { 
    if (txtICode.IsFocused != true) 
    { 
     if (NewData) 
     { 
      if (txtICode.Text != null) 
      { 
       if (txtICode.Text != "") 
       { 
        Item temp = new Item(); 
        Item[] list = temp.Query(new object[] { Item.DataEnum.Item_Code }, new string[] { txtICode.Text }); 
        if (list.Length > 0) 
        { 
         System.Windows.Forms.MessageBox.Show("This item code is already being used.", "Invalid information"); 
         txtICode.Focus(); 
         return; 
        } 
       } 
      } 
     } 
    }); 
} 
0
  private void txtICode_LostFocus(object sender, RoutedEventArgs e) 
      { 
       string inputText = txtICode.Text; 
       if (string.IsNullOrEmpty(inputText) || !NewData) 
       { 
        return; 
       } 
       Item temp = new Item(); 
       Item[] list = temp.Query(new object[] { Item.DataEnum.Item_Code }, 
                 new string[] { inputText }); 
       if (list != null && list.Length > 0) 
       { 
        MessageBox.Show("This item code is already being used.", "Invalidinformation"); 
        txtICode.Focus(); 
        return; 
       } 
      }