在我的程序中,我有一个按钮点击,从该onclick事件我调用一个方法进行一些文本框验证。代码是:
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation();
//Some other Code
}
public void CheckValidation()
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
//Some other Code
}
如果txtphysi.text
为null,则它进入循环并使用return然后它仅来自CheckValidation()
方法并且它继续在btnupdate_Click
事件中,但在这里我想要停止btnupdate_Click
中的执行过程也是如此。我该怎么做?
答案 0 :(得分:9)
我的理解是非常简单的编程逻辑,你需要在这里申请..
这是从Boolean
方法而不是返回CheckValidation()
返回void
,以便父函数从函数的执行中知道状态。
protected void btnupdate_Click(object sender, EventArgs e)
{
var flag = CheckValidation();
if(!flag)
return;
//Some other Code
}
public bool CheckValidation()
{
var flag = false; // by default flag is false
if (string.IsNullOrWhiteSpace(txtphysi.Text)) // Use string.IsNullOrWhiteSpace() method instead of Trim() == "" to comply with framework rules
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return flag;
}
//Some other Code
flag = true; // change the flag to true to continue execution
return flag;
}
答案 1 :(得分:4)
实现这一目标:
1)将CheckValidation()
方法的返回类型更改为bool。在btnupdate_Click()
方法中,按照
if(!CheckValidation())
{
return;
}
希望有所帮助。
答案 2 :(得分:2)
如果这是您已将其标记为的ASP.NET,那么您应该使用RequiredFieldValidator(对于webforms),如果您使用的是MVC,则可以使用DataAnnotations:http://forums.asp.net/t/1983198.aspx?RequiredFieldValidator+in+MVC
答案 3 :(得分:2)
虽然答案已被接受,但我认为将代码放入事件中并不是一个好习惯。最好将代表用于此类目的。
public class Sample
{
public Sample()
{
UpdateAction = OnUpdate;
}
Action UpdateAction = null;
private void OnUpdate()
{
//some update related stuff
}
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation(UpdateAction);
}
public void CheckValidation(Action action)
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
action();
}
}
答案 4 :(得分:0)
这里试试这个:
protected void btnupdate_Click(object sender, EventArgs e)
{
if(!CheckValidation())
{
//Some other Code
}
}
public bool CheckValidation()
{
if (string.isnullorEmpty(txtphysi.Text.Trim()) )
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return false;
}
else
{
//Some other Code
return true;
}
}