我试图遵循Control.Validating Event的MSDN示例代码,并将其应用于bindingNavigator项,而不是textbox,如示例中所示。
为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);
}
}我也打算验证文本框,但是我有几个,并且已经为它们编写了验证方法,这些方法处理错误消息。当用户在bindingNavidator上选择一个项(箭头按钮/保存按钮/添加按钮)时,我希望测试这些方法。
因此,我有下面的代码来尝试,
private void myBindingNavigator_Validating(object sender, CancelEventArgs e)
{
if (!IsPostCodeValid())
{
PostCodeTextBox.Focus();
e.Cancel = true;
}
}我将bindingNavigator的bindingNavigator事件设置为bindingNavigator.Focus(),希望启动验证事件。(myBindingNavigator.CausesValidation = true;已在formLoad上声明)。然而,我觉得这是一个无限循环的聚焦导航条跟随?我已经迈出了一步,一旦它锁定在导航栏上,就不会执行任何代码,它根本不会让用户在导航栏被锁定后与表单的其余部分交互来更改和更正错误。
我可以提供任何额外的信息,并测试任何建议,以发现发生了什么。
谢谢
发布于 2015-12-31 18:50:56
当您使用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属性,并将MoveFirstItem、MovePreviousItem、MoveNextItem、MoveLastItem、AddNewItem、DeleteItem属性设置为(none)。另外,从designer单击显示记录号的文本框中,它是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();`
}https://stackoverflow.com/questions/34546505
复制相似问题