bindingNavigator _验证未将控件返回到表单的事件

本文关键字:表单 事件 返回 控件 验证 bindingNavigator | 更新日期: 2023-09-27 18:28:38

我正试图遵循MSDN中Control.Validating Event的示例代码,并将其应用于bindingNavigator项,而不是示例中的textbox

为文本框验证事件提供的代码如下所示。

private void textBox1_Validating(object sender, 
                System.ComponentModel.CancelEventArgs e)
{
   string errorMsg;
   if(!ValidEmailAddress(textBox1.Text, out errorMsg))
   {
      // Cancel the event and select the text to be corrected by the user.
      e.Cancel = true;
      textBox1.Select(0, textBox1.Text.Length);
      // Set the ErrorProvider error with the text to display. 
      this.errorProvider1.SetError(textBox1, errorMsg);
   }
}

我也打算验证texbox,但我有几个,并且已经为它们编写了处理错误消息的验证方法。我希望当用户在bindingNavidator上选择一个项目(箭头按钮/保存按钮/添加按钮)时测试这些方法。

因此,我有下面的代码来尝试这个,

private void myBindingNavigator_Validating(object sender, CancelEventArgs e)
{
  if (!IsPostCodeValid())
  {
    PostCodeTextBox.Focus();
    e.Cancel = true;   
  }
}

我将bindingNavigator的ItemClicked事件设置为bindingNavigator.Focus(),希望启动Validating事件。(myBindingNavigator.CausesValidation = true;已在formLoad上声明)。然而,我觉得这就是聚焦导航栏的无限循环?我已经完成了步骤,一旦它锁定到导航栏,就不会执行任何代码——它只是不允许用户在锁定导航栏后与表单的其他部分交互来更改和更正错误。

我可以提供任何所需的额外信息,并测试任何建议,以发现发生了什么。

感谢

bindingNavigator _验证未将控件返回到表单的事件

当您使用BindingNavigator并将控件置于表单的详细信息模式时,为了确保只保存有效数据,您应该为控件编写验证规则,还应该自己处理绑定导航器项。

通过这种方式,您甚至不需要将表单的AutoValidate属性设置为烦人的EnablePreventFocusChange,并且您可以将其设置为友好的EnableAllowFocusChange,因为当出现验证错误时,您无法导航或保存任何内容,因此您可以确保只有有效数据会保存在数据库中。

为此,请执行以下步骤:

步骤1

处理子控件的Validating事件,当值无效时设置e.cancel = true

private void nameTextBox_Validating(object sender, CancelEventArgs e)
{
    //Put validation logic here
    if (this.nameTextBox.Text.Length < 10)
    {
        e.Cancel = true;
        this.errorProvider1.SetError(this.nameTextBox, "Some Error");
    }
    else
    {
        this.errorProvider1.SetError(this.nameTextBox, "");
    }
}

步骤2

转到BindingNavigator属性,然后将MoveFirstItemMovePreviousItemMoveNextItemMoveLastItemAddNewItemDeleteItem属性设置为(none)。此外,在设计器中,单击显示记录编号的文本框,即bindingNavigatorPositionItem,然后将其ReadOnly属性设置为true

步骤3

对于所有按钮,包括导航按钮、添加按钮、删除按钮、保存按钮和其他自定义按钮,处理Click事件并调用文本框容器的ValidateChildren方法,检查ValidateChildren()是否不返回true,退出该方法,否则执行该方法应执行的任务,例如:

private void toolStripButton1_Click(object sender, EventArgs e)
{
    if (!this.ValidateChildren())
        return;
    //Put the logic for this button here
    //MoveFirstItem: `this.myBindingSource.MoveFirst();`
    //MovePreviousItem: `this.myBindingSource.MovePrevious();`
    //MoveNextItem: `this.myBindingSource.MoveNext();`
    //MoveLastItem: `this.myBindingSource.MoveLast();`
    //AddNewItem: `this.myBindingSource.AddNew();`
    //DeleteItem: `this.myBindingSource.RemoveCurrent();`
}