Click here to Skip to main content
15,891,204 members
Articles / Programming Languages / C#
Tip/Trick

How to prompt the user for data and conditionally prevent a Windows Forms app from Starting

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
23 Jan 2015CPOL1 min read 13.3K   5   7
Quick-and-Dirty conditional suppression of a Windows Forms app / main form in three easy steps

Through the Rompecabeza Gauntlet

Sometimes you want certain data from a user of your app before the app starts and may want to disallow the app from running if they don't provide what you want. For instance, you may want to record them pronouncing the word "Shibboleth" and compare their attempt at proper elocution of that word with what you consider to be the correct way; if they fail, don't allow them to run the app. Or...you might have other tests you want them to pass, or simply want to gather some info before proceeding and, if they are not willing to provide it, to perdition with them! Well, at least, don't let them run the app...

Anyway, in a Windows form app, you can do this pretty easily. Here's one way:

0) Add the values you want to prompt the user for in a global location, such as a Consts class:

C#
public static class DbillPlatypusConsts
{
    public static string userName; 
    public static string pwd;
    public static string platypupRompecabeza;
	. . .

1) Create a "login" (or "prompt" or "test" or whatever you want to call it) form. Add labels and textboxes to prompt the user for these values and give them a way to provide them; also, add an "OK" button and a "Cancel" button. That file can be something like this:

C#
public partial class frmLogin : Form
{
    // Make the entries available via properties
    public string UserName { get { return textBoxUsername.Text.Trim(); } }
    public string Password { get { return textBoxPwd.Text.Trim(); } }
    public string PlatypupRompecabeza { get { return textBoxPlatypupRompecabeza.Text.Trim(); } }

    public frmLogin()
    {
        InitializeComponent();
    }

    private void buttonClose_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Cancel;
    }

    private void buttonOK_Click(object sender, EventArgs e)
    {
        if (SanityCheck())
        {
            this.DialogResult = DialogResult.OK; 
        }
    }

    // Prior to the more rigorous gauntlet to come, in Program.cs, make sure that they at least enter something
    private bool SanityCheck()
    {
        bool pass = ((!(String.IsNullOrEmpty(textBoxUsername.Text.Trim()))) &&
                     (!(String.IsNullOrEmpty(textBoxPwd.Text.Trim()))) &&
                     (!(String.IsNullOrEmpty(textBoxPlatypupRompecabeza.Text.Trim()))));
        if (!pass)
        {
            MessageBox.Show("You have not yet provided some key data; be sure to enter a username, password, and a platypup rompecabeza!");
        }
        return pass;
    }

2) Add code to Program.cs to invoke that form and conditionally run the app/main form:

C#
static class Program
{
    [MTAThread]
    static void Main()
    {
        frmLogin loginForm;
        using (loginForm = new frmLogin())
        {
            if (loginForm.ShowDialog() == DialogResult.OK)
            {
                DbillPlatypusConsts.userName = loginForm.UserName;
                DbillPlatypusConsts.pwd = loginForm.Password;
                DbillPlatypusConsts.platypupRompecabeza = loginForm.PlatypupRompecabeza;
                // Verify that these vals are valid
                if ((DbillPlatypusConsts.userName == "Ephraim") && 
                    (DbillPlatypusConsts.pwd == "goSeahwaks_brattyIsAPunkAndBellychunksIsAWeasel") && 
                    (DbillPlatypusConsts.platypupRompecabeza == "defl8G8"))
                    {
                        Application.Run(new frmMain());
                    }
                }
            }
        }

Pre-emptive Thumb-nosing

No doubt some fancy-pants, propellor-head supergeeks will poke holes in this methodology, but it works for me/meets me semi-tough standards.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionNo holes to poke... Pin
bojammis26-Jan-15 8:03
professionalbojammis26-Jan-15 8:03 
GeneralThoughts Pin
PIEBALDconsult24-Jan-15 4:27
mvePIEBALDconsult24-Jan-15 4:27 
GeneralRe: Thoughts Pin
B. Clay Shannon24-Jan-15 4:47
professionalB. Clay Shannon24-Jan-15 4:47 
GeneralRe: Thoughts Pin
PIEBALDconsult24-Jan-15 4:56
mvePIEBALDconsult24-Jan-15 4:56 
GeneralRe: Thoughts Pin
B. Clay Shannon27-Jan-15 5:53
professionalB. Clay Shannon27-Jan-15 5:53 
GeneralRe: Thoughts Pin
PIEBALDconsult27-Jan-15 12:28
mvePIEBALDconsult27-Jan-15 12:28 
Questionthank you! Pin
manchanx23-Jan-15 15:58
professionalmanchanx23-Jan-15 15:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.