我在我的表单中有一个文本框供用户键入项目代码。当textbox的焦点丢失时,它将查看数据库,以检查项目代码是否存在。然而,当我试图通过单击其他文本框来失去焦点时,我会得到无限循环。
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。
发布于 2013-04-10 12:21:25
您不必在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");
}
}发布于 2013-04-10 12:22:22
您可以使用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;
}
}
}
}
});
}发布于 2013-04-10 12:25:34
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;
}
}https://stackoverflow.com/questions/15916743
复制相似问题