Jithu Jithu - 2 months ago 5
ASP.NET (C#) Question

How use return between methods

In my Program I have a button click, from that onclick event I am calling one method for some textbox validation. The code is:

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
}


Here if
txtphysi.text
is null then it comes into loop and use return then it came from the
CheckValidation()
method only and it continues in
btnupdate_Click
event, but here I want to stop the execution process in
btnupdate_Click
also. How can I do it?

Answer

It is very simple programming logic in my understanding that you need to apply here..

That is return Boolean from CheckValidation() method instead of return void so that parent function knows the state from the function's execution.

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;
}