Input and Output Statements
AAHC

Click on A to make all fonts on the page smaller.

Click on A to make all fonts on the page larger.

Click on HC to toggle high contrast mode. When you move your mouse over some bold words in high contrast mode, related words are automatically highlighted. Text is shown in black and white.


Programming and logic are wonderful things, but they don't exist in a vacuum. They need to get information from, and return it to, their creators. In this lesson, we'll learn about how to perform input and output. We've already seen output by writing to the Console, but now we'll expand our arsenal to include writing output to the screen, and to a file, as well as reading input from the screen and a file. We'll also learn the difference between a Windows application and a console application, and how they differ when it comes to input and output. Let's get started!

Windows GUI Application Versus Console Application

So far, for every application we've created, we've selected the default Windows Forms Application. You probably noticed that there are quite a few other types of projects we could create, such as a Console Application. A Console Application runs as a command-line application, without the graphical windows we've become so used to. A Console Application can have a GUI (graphical user interface), but it isn't constructed using the Microsoft Windows GUI components. Many older applications are console GUI applications. Also, numerous command-line/console applications exist on whatever operating system you're using, adding functionality that does not require a GUI for user interaction. Depending on your operating system, you may have heard of a command prompt, DOS prompt, MS-DOS prompt, or command-line window. Fortunately for us, when you create a Console Application and execute it, Studio opens a command-line window, or console window, and executes the application. Because a command-line application executes then ends without a GUI, we will add functionality to the end of our Console Application to allow it to pause before the console window closes.

Let's create our first Console Application before we move on to input and output statements.

Simple Console Input and Output

Select File | New | Project. In the center section of the New Project dialog box, select Console Application. Change the Name of the project to ConsoleIOs. All other dropdowns and check boxes take their default settings:

Click OK. After you've created the new Console Application project, you'll notice a few differences: the code in the Visual Editor is different, including the using statements, there is no Form class (Form1.cs), and the default class for the C# source code is Program.cs. Let's look at the default code.

OBSERVE: ConsoleIO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleIO
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

It turns out that our Windows Forms Application also has a Program.cs file, but we've never discussed this file yet. Both a Console Application and a Windows Forms Application must have what is known as an entry point: the code that is first called when the application starts. For both types of applications, the code in a Main method is first called. In a Windows Forms Application, we've always skipped the Main code and gone right to the Form, as that is where we needed to add our controls and code to get the application going. With a Console Application, we will work directly within Main.

A Console Application can have optional command-line parameters passed to it. These command-line parameters would be available to our code in the args parameter of Main. Also, you'll notice a new keyword: static. Using the static keyword means that there is only one, and in our case, that makes sense, as we only want one entry point into our program. We'll discuss static more in later lessons, as for now we're mainly interested in input and output. Let's add some output to our program.

Modify Console.cs as shown below.

ConsoleIO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleIO
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("My first console application!");
            
            // Keep the console open in debug mode.
            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
    }
}
        

and to run the program

.

You've seen the Console.WriteLine() method many times before, but we did add a line of code that is actually our first input statement: Console.ReadKey(). This method waits until any key is pressed. Once a key is pressed, the ReadKey() method allows the program to continue, effectively creating the pause in the program we mentioned. You can try to click on the console window to see if it will let the program close. It won't.

Let's introduce some other ways we can get keyboard input.

For console input, there are three basic routines you can use to read data directly from the keyboard:

Modify Console.cs as shown below.

ConsoleIO.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleIO
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("My first console application!");
            
            bool quitLoop = false;
            bool interceptKey = true;
            
            // Use ReadKey.
            Console.WriteLine("\nPress any key; then, press Enter to exit.\n");
            do
            {
                Console.Write("> ");
                ConsoleKeyInfo keyInfo = Console.ReadKey(interceptKey);
                if (keyInfo.Key == ConsoleKey.Enter)
                    quitLoop = true;
                    Console.WriteLine("You pressed: " + keyInfo.Key);
            } while (!quitLoop);
            
            // Use ReadLine.
            Console.WriteLine("\nType in any characters; press Enter to exit.\n");
            do
            {
                Console.Write("> ");
                string enteredLine = Console.ReadLine();
                if (enteredLine.Length == 0)
                    break;
                Console.WriteLine("You typed {0} character" + (enteredLine.Length > 1 ? "s." : "."), enteredLine.Length);
            } while (true);
            
            // Keep the console open in debug mode.
            Console.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
    }
}

and to run the program and follow the onscreen instructions.

Let's discuss how this code works.

OBSERVE: ConsoleIO.cs
.
.
.
            // Use ReadKey.
            Console.WriteLine("\nPress any key; then, press Enter to exit.\n");
            do
            {
                Console.Write("> ");
                ConsoleKeyInfo keyInfo = Console.ReadKey(interceptKey);
                if (keyInfo.Key == ConsoleKey.Enter)
                    quitLoop = true;
                Console.WriteLine("You pressed: " + keyInfo.Key);
            } while (!quitLoop);
.
.
.

We used the Console.ReadKey() and ReadLine() methods to process user input. The ReadKey uses a do..while loop to continue to take user input from the keyboard until the user presses Enter on a blank line (which will ultimately set quitLoop to true, providing a means to exit the loop). We store information about the key pressed in keyInfo. You'll notice that we pass interceptKey (with a value of true) to Console.ReadKey to suppress the display of the key pressed by the user. We then extract the key pressed and output it using keyInfo.Key, comparing the key pressed to ConsoleKey.Enter to see if we need to exit.

OBSERVE: ConsoleIO.cs
.
.
.
            // Use ReadLine.
            Console.WriteLine("\nType in any characters; press Enter to exit.\n");
            do
            {
                Console.Write("> ");
                string enteredLine = Console.ReadLine();
                if (enteredLine.Length == 0)
                    break;
                Console.WriteLine("You typed {0} character" + (enteredLine.Length > 1 ? "s" : ""), enteredLine.Length);
            } while (true);
.
.
.

For ReadLine(), we again use a do..while loop, but this time we use a conditional statement of true, which means that the do..while loop will loop forever unless we use another mechanism to exit. In this case, we use a break statement when the user presses Enter on a blank line. The Console.ReadLine() method accepts multiple characters until Enter is pressed. We store the entered characters in enteredLine. We check the length of enteredLine and if no characters were entered, we use break to exit the loop. We output the number of typed characters using formatted output ({0}), and the conditional/ternary operator (? :) to determine if we need to add an "s" (if more than one character was entered).

You may notice that we used both output versions of Console: Write() and WriteLine(). WriteLine automatically includes a carriage return when it writes, whereas a Write does not, allowing the prompt for the Console.ReadLine() (and Console.ReadKey()) to follow after the prompt (> ).

So, that's simple input and output from a console application. What about from a GUI? Let's make a new project to explore input and out from a Windows Forms Application.

GUI Input and Output

We've already seen a number of ways to output information to a user using a variety of controls: Labels, TextBoxes, ListBoxes, drawing directly to a form, etc. We've also used quite a few controls to get input from a user. What we haven't done yet is to create a new Form with our Windows Forms Application that might serve as a dialog box. What is a dialog box? A dialog box is a window that appears in front of all other windows. As discussed earlier, they can be of two types: modal dialog boxes must be dismissed before control can be passed back to the calling program; modeless dialog boxes do not require being dismissed, allowing the user to interact with the calling program while the dialog box remains visible. For the project for this lesson, we want a modal dialog box to force the user to either enter the desired information, or to dismiss/cancel the dialog box, before they continue working.

Dialog boxes also have a few unique GUI properties: they typically cannot be resized (exceptions are allowed), they may not have the usual Windows controls (minimize, maximize, close, or the system icon) at their top left and top right, and do not appear up in the Windows Taskbar. Basically, the intent of a dialog box is to alert the user of an immediate need for input, or to convey some type of information, before the program can continue. As the developer, you do have the freedom to create dialog boxes as you desire depending on the user interaction you want or need to make your program work. Microsoft does have a number of articles that constitute a style guide or user experience guidelines for dialog boxes that you may want to research, but in general you can observe the behavior of existing Windows software for examples of what you can do.

Let's create a Dialog Box Form to request user input.

Select File | New | Project. Change the name to FormsIO, and make sure Windows is selected under the C# tree item, and Windows Forms Application is selected in the center section (this will have changed after our last project). All other dropdowns and check boxes take their default settings. Click OK.

Rename the file Form1.cs to FormsIO.cs. Change the form's title bar Text property in the Properties Window from Form1 to Forms IO. Click to save your changes.

Adding a Label control and a Button control. Change the Label control Name property to hiLabel and Text property to Hi. Change the Button control Name property to dialogButton and Text property to Dialog. Double-click the dialogButton control to add an event handler for the button. Click to save your changes.

Next, we'll add a new Form to our project that will become our popup dialog box.

In the Solution Explorer, right-click the FormsIO project name, and select Add | Windows Form...:

In the Add New Item - FormsIO dialog box, make sure that Windows Form is selected. Change the Name field to Popup.cs, and then click Add.

Now that we've added the new Popup Form, let's add a few controls, and change the size of the form.

Modify the Popup Form by adding the controls listed below. Change each control's Name property to match the Name Property column, and each Text property to match the Text Property column. Arrange the controls and resize the form as shown:

ObjectName PropertyText Property
LabelnameLabelEnter Name:
TextBoxnameTextBox
ButtonokButtonOK
ButtoncancelButtonCancel

Click to save your changes.

We also need to add the Button event handlers, and change some of the Form properties to turn the Form into the type of dialog box we want (and explore more of the Form properties along the way).

Double-click each Button to generate an event handler. Modify the Popup Form properties in the Properties Window using the list below. Remember to click on the Popup Form in the Visual Designer to select it. Change each property to the specified value. When you finish, click to save your changes.

PropertyValue
AcceptButtonokButton
CancelButtoncancelButton
ControlBoxFalse
FormBorderStyleFixedDialog
ShowInTaskbarFalse
StartPositionCenterParent

Note When you try to set the AcceptButton and CancelButton properties, if you do not find the Value listed in the table, you need add the event handler for the Button.

So what exactly do each of these properties do? Rather than list out what each property does, let's learn by doing.

In the Properties Window, click on each of the Popup Form properties listed above, then look below the Properties Window to find the Properties Help Window that describes each property. For example, for the AcceptButton property, you should see:

The accept button of the form. If this is set, the button is 'clicked' whenever the user presses the 'ENTER' key.

Now, let's go back to the FormsIO Form and call the Popup dialog box Form.

Select the FormsIO.cs Code Editor tab, and modify the code as shown below.

FormsIO.cs
using ...

namespace FormsIO
{
    public partial class FormsIO : Form
    {
        public FormsIO()
        {
            InitializeComponent();
        }
        
        private void dialogButton_Click(object sender, EventArgs e)
        {
            Popup myPopup = new Popup();
            myPopup.ShowDialog();
        }
    }
}
        

and to run the program. Click Dialog to see the dialog box we created. You can't really do much of anything with it yet, so click OK or Cancel, and then close the

Let's discuss how this code works.

OBSERVE: FormsIO.cs
.
.
.

        private void dialogButton_Click(object sender, EventArgs e)
        {
            Popup myPopup = new Popup();
            myPopup.ShowDialog();
        }
.
.
.

Now that we've created the Popup Form, we can use that Form as a data type, declaring the variable myPopup, and creating an instance of the Popup Form. We then call the ShowDialog() method of the myPopup Form, which will display our new dialog box.

Next, we need to modify the Popup Form to act like a dialog box and return the button selected entered by the user.

Switch to the Popup.cs [Design] tab. Click the okButton and change the DialogResult property to OK. Click the cancelButton and change the DialogResult property to Cancel. Then, modify the code in Popup.cs as shown below.

Popup.cs
using ...

namespace FormsIO
{
    public partial class Popup : Form
    {
        private string _userName = "";
        
        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
        
        public Popup()
        {
            InitializeComponent();
        }
        
        private void okButton_Click(object sender, EventArgs e)
        {
            _userName = nameTextBox.Text;
            this.Close();
        }
    }
}

to save your changes. You can still run it without error, but it won't look any different yet. Let's discuss the new code.

OBSERVE: Popup.cs
.
.
.
        private string _userName = "";
        
        public string UserName
        {
            get { return _userName; }
            set { _userName = value; }
        }
.
.
.
        private void okButton_Click(object sender, EventArgs e)
        {
            _userName = nameTextBox.Text;
            this.Close();
        }

We added a private variable _userName to hold whatever the user might enter. We also added accessors for this variable. If the user clicks the okButton, we will set the _userName variable and Close() the Form. (We don't need to handle the Cancel event; the CancelButton took care of that for us.

Finally, we need to modify the FormsIO Form to be able to determine which button was clicked, and retrieve the information entered.

Select the FormsIO.cs Form Code Editor, and modify the code as shown below.

FormsIO.cs
using ...

namespace FormsIO
{
    public partial class FormsIO : Form
    {
        public FormsIO()
        {
            InitializeComponent();
        }
        
        private void dialogButton_Click(object sender, EventArgs e)
        {
            Popup myPopup = new Popup();
            
            myPopup.ShowDialog();
            if (myPopup.ShowDialog() == DialogResult.OK)
            {
                hiLabel.Text = "Hi, " + myPopup.UserName;
            }
            else
            {
                hiLabel.Text = "So don't tell me your name.";
            }
        }
    }
}
        

and to run the program. Click Dialog, enter your name, and click OK, and "Hi, your name" should appear in the form. Click Dialog and click Cancel, and "So don't tell me your name." should appear in the form.

Let's discuss how this code works.

OBSERVE: FormsIO.cs
.
.
.
        private void dialogButton_Click(object sender, EventArgs e)
        {
            Popup myPopup = new Popup();
            
            if (myPopup.ShowDialog() == DialogResult.OK)
            {
                hiLabel.Text = "Hi, " + myPopup.UserName;
            }
            else
            {
                hiLabel.Text = "So don't tell me your name.";
            }
.
.
.

We've modified the FormsIO code to check if the myPopup.ShowDialog() method returns a value of DialogResult.OK, indicating the user clicked on the okButton on the Popup Form. If the okButton was clicked, then we can go ahead and access the data the user entered (if any) by calling the myPopup.UserName method. If not (they clicked the cancelButton), then we'll just have to let them know.

So, that's how to add your own custom dialog box!

Before you move on to the next lesson, do your homework! Right-click in the window where this lesson text appears and select Back. Then select Quiz for this lesson in the syllabus and answer the quiz questions. When you finish the quiz questions, click Hand it in at the bottom of that window. Then do the same with the Project(s) for the lesson. Your instructor will grade your quiz(zes) and project(s) and provide guidance if needed.