Quitting before you've started

  • Thread starter Thread starter BMC
  • Start date Start date
B

BMC

When starting up, my app needs to pull some information out of a
database, which it does. It also needs to quit if the SQL query returns
no data.

All the database checking stuff is in a private void that is called
right after the InitializeComponent() on the form.

The code in that function that determines that it should quit is this:

if (!reader.HasRows)
{
MessageBox.Show("Unknown user.");
Application.Exit();
}

Now when that criteria is met, the message box shows but the application
doesn't quit. If I run that same function by e.g. attaching it to the
click event of something, it does work and shut the application down.

Any ideas what I might be doing wrong here?
 
Lets assume your form is called Form1. The Main of your app probably contains

Application.Run(new Form1());

The issue is that you have your function call in the constructor for Form1.
That means it gets called in the form before the Form is passed to
Application.Run()
That means the Application isn't running a form and therefore it wont do
anything to exit. You would be best to move the logic into the Main method if
the reader has no rows, return from Main without calling Application.Run.
This will stop the app bothering to load the form to never show it too.

Ciaran O'Donnell
 
Are you expecting the application to quit before the user has dismissed
the MessageBox? If so, that's never going to happen, by design.

When you say it doesn't quit, what is it not doing that you expect it
to do?


Stephan
 
Thank you very much for the explanation; I now understand why it
wouldn't work.

I've copied some of the database checking function into the static void
main() in program.cs, and only calling Application.Run if rows are
returned. This works.
 
Back
Top