Exiting a Subroutine

  • Thread starter Thread starter OutdoorGuy
  • Start date Start date
O

OutdoorGuy

Greetings,

I'm still relatively new to C# and was wondering if there was a way to
exit a subroutine (such as "Exit Sub" in VB)? I have the code below
which performs validations. If the user fails to enter in a First name,
then I want to set the focus to the control on the form and then exit
the subroutine. Any ideas?

private void btnSubmit_Click(object sender, System.EventArgs e)
{
...

if (this.txtFirstName.Text == "")
{
MessageBox.Show("First Name is required");
this.txtFirstName.Focus();
// I then want to exit the subroutine.
}
if (Lastname == "")
{
...

Thanks in advance!
 
yes, just call,

return ""; or whatever you want. The return call will cause the function to
exit at that point...

glenn
 
Hey,

You can use the return keyword for this:

if (this.txtFirstName.Text == "")
{
MessageBox.Show("First Name is required");
this.txtFirstName.Focus();
return;
}

Hope that helps,
Clint
 
Just use "return":

private void btnSubmit_Click(object sender, System.EventArgs e)
{
...
if (this.txtFirstName.Text == "")
{
MessageBox.Show("First Name is required");
this.txtFirstName.Focus();
// I then want to exit the subroutine.
return; <-------
}
 
Thanks, Clint. That seems to do the trick. However, my "Focus()"
statement is not working. I am using a tab control, so could this be
the issue? The control I want to set the focus to (i.e.,
"txtFirstname") is on the first "tab page". Do I first need to navigate
to the tab page and then set the focus to the appropriate control?

Thanks again!
 
OutdoorGuy said:
Thanks, Clint. That seems to do the trick. However, my "Focus()"
statement is not working. I am using a tab control, so could this be
the issue? The control I want to set the focus to (i.e.,
"txtFirstname") is on the first "tab page". Do I first need to navigate
to the tab page and then set the focus to the appropriate control?

Thanks again!

I believe you do have to set the correct tab first, then call Focus().
Out of curiousity, did this work correctly before the "return;" was put
in?
 
Thanks for the info, Clint. I simply had to use the "Show" method of
the tab page object and then use the "Focus" method to set the focus to
the appropriate control. (See sample code below).

In answer to your question, the "Focus" method didn't work before I put
in the "Return" statement either. The key was simply selecting the tab
page first.

if (this.txtLastName.Text == "")
{
this.tabPage1.Show();
MessageBox.Show("'Last Name' is required");
this.txtLastName.Focus();
return;
}

Thanks again!
 
Back
Top