我有一个表单,可以通过ValidateChildren
方法在保存按钮上验证。
Id
字段还有一个validating
和一个validated
,可以从数据库中快速重新加载(不同的)文档。
实际问题是我提交表单的时候:IdText
控件一定不能完全验证,否则模型将重新加载。溶液
private void IdText_Validating(object sender, CancelEventArgs e)
{
try
{
int n = 0;
var isNumeric = int.TryParse(IdText.Text, out n);
if (!isNumeric)
{
e.Cancel = true;
throw new Exception("Valore inserito non valido");
return;
}
dxErrorProvider.SetError(IdText, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Errore", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
private void IdText_Validated(object sender, EventArgs e)
{
try
{
int n = 0;
var isNumeric = int.TryParse(IdText.Text, out n);
if (!isNumeric) throw new Exception("Valore inserito non valido");
model = Registrazione.Manager.GetRegistrazione(n);
if (model == null) throw new Exception("Registrazione con id " + n + " non trovata.");
model.PropertyChanged += OnModelPropertyChanged;
BindMovimentiEventHandlers(null, null);
CaricamentoRegistrazione_Load(sender, null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Errore", MessageBoxButtons.OK,
MessageBoxIcon.Error); return;
}
}
答案 0 :(得分:0)
我发现覆盖ValidateChildren
是实现我真正想要的可能解决方案之一,然后创建一个方法来捕获每个控件的Validating
事件处理程序,但是,我知道反思及其不安全感。代码:
public override bool ValidateChildren()
{
bool allValid = true;
foreach (Control control in this.Controls)
{
if (control.Name == "Id")
{
continue;
}
if (!control.IsValid())
{
allValid = false;
}
}
return allValid;
}
public static bool IsValid(this Control controlToValidate)
{
Debug.Assert(controlToValidate != null, "Control to validate is null");
Type t = typeof(Control);
MethodInfo mi = t.GetMethod("NotifyValidating", BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.InvokeMethod);
Debug.Assert(mi != null, "Could not get method information.");
return !((Boolean)mi.Invoke(controlToValidate, null));
}