我有两个文本框,分别是to_date和from_date。 我比较了两个文本框并获取值,但它的执行发生在我要停止的按钮旁边,因为如果to_date小于开始日期,则结束日期变为 null,并专注于文本框不去单击按钮的事件。
我使用 :
try
{
DateTime from = DateTime.ParseExact(txt_from_date.Text, "M/d/yyyy", theCultureInfo);
DateTime to = DateTime.ParseExact(txt_to_date.Text, "M/d/yyyy", theCultureInfo);
int result = DateTime.Compare(to, from);
e.IsValid = result>0;
if (e.IsValid == false)
{
txt_to_date.Text = "";
txt_to_date.Focus();
}
}
catch (Exception eq)
{
e.IsValid = false;
txt_to_date.Text = "";
}
如果是 onclick 事件处理程序,则必须调用验证:
protected void YourButton_OnClick(object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid) // Will be false if any validator is invalid
{
// your code here
}
}
请注意,如果必须将窗体拆分为多个子部分,则可以在验证控件上设置ValidationGroup
并将相同的值传递给Page.Validate
方法。