2013-04-10 44 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; 
       } 
      }