- •Microsoft C# Programming for the Absolute Beginner
- •Table of Contents
- •Microsoft C# Programming for the Absolute Beginner
- •Introduction
- •Overview
- •Chapter 1: Basic Input and Output: A Mini Adventure
- •Project: The Mini Adventure
- •Reviewing Basic C# Concepts
- •Namespaces
- •Classes
- •Methods
- •Statements
- •The Console Object
- •.NET Documentation
- •Getting into the Visual Studio .Net Environment
- •Examining the Default Code
- •Creating a Custom Namespace
- •Adding Summary Comments
- •Creating the Class
- •Moving from Code to a Program
- •Compiling Your Program
- •Looking for Bugs
- •Getting Input from the User
- •Creating a String Variable
- •Getting a Value with the Console.ReadLine() Method
- •Incorporating a Variable in Output
- •Combining String Values
- •Combining Strings with Concatenation
- •Adding a Tab Character
- •Using the Newline Sequence
- •Displaying a Backslash
- •Displaying Quotation Marks
- •Launching the Mini Adventure
- •Planning the Story
- •Creating the Variables
- •Getting Values from the User
- •Writing the Output
- •Finishing the Program
- •Summary
- •Chapter 2: Branching and Operators: The Math Game
- •The Math Game
- •Using Numeric Variables
- •The Simple Math Game
- •Numeric Variable Types
- •Integer Variables
- •Long Integers
- •Data Type Problems
- •Math Operators
- •Converting Variables
- •Explicit Casting
- •The Convert Object
- •Creating a Branch in Program Logic
- •The Hi Bill Game
- •Condition Testing
- •The If Statement
- •The Else Clause
- •Multiple Conditions
- •Working with The Switch Statement
- •The Switch Demo Program
- •Examining How Switch Statements Work
- •Creating a Random Number
- •Introducing the Die Roller
- •Exploring the Random Object
- •Creating a Random Double with the .NextDouble() Method
- •Getting the Values of Dice
- •Creating the Math Game
- •Designing the Game
- •Creating the Variables
- •Managing Addition
- •Managing Subtraction
- •Managing Multiplication and Division
- •Checking the Answers
- •Waiting for the Carriage Return
- •Summary
- •Chapter 3: Loops and Strings: The Pig Latin Program
- •Project: The Pig Latin Program
- •Investigating The String Object
- •The String Mangler Program
- •A Closer Look at Strings
- •Using the Object Browser
- •Experimenting with String Methods
- •Performing Common String Manipulations
- •Using a For Loop
- •Examining The Bean Counter Program
- •Creating a Sentry Variable
- •Checking for an Upper Limit
- •Incrementing the Variable
- •Examining the Behavior of the For Loop
- •The Fancy Beans Program
- •Skipping Numbers
- •Counting Backwards
- •Using a Foreach Loop to Break Up a Sentence
- •Using a While Loop
- •The Magic Word Program
- •Writing an Effective While Loop
- •Planning Your Program with the STAIR Process
- •S: State the Problem
- •T: Tool Identification
- •A: Algorithm
- •I: Implementation
- •R: Refinement
- •Applying STAIR to the Pig Latin Program
- •Stating the Problem
- •Identifying the Tools
- •Creating the Algorithm
- •Implementing and Refining
- •Writing the Pig Latin Program
- •Setting Up the Variables
- •Creating the Outside Loop
- •Dividing the Phrase into Words
- •Extracting the First Character
- •Checking for a Vowel
- •Adding Debugging Code
- •Closing Up the code
- •Summary
- •Introducing the Critter Program
- •Creating Methods to Reuse Code
- •The Song Program
- •Building the Main() Method
- •Creating a Simple Method
- •Adding a Parameter
- •Returning a Value
- •Creating a Menu
- •Creating a Main Loop
- •Creating the Sentry Variable
- •Calling a Method
- •Working with the Results
- •Writing the showMenu() Method
- •Getting Input from the User
- •Handling Exceptions
- •Returning a Value
- •Creating a New Object with the CritterName Program
- •Creating the Basic Critter
- •Using Scope Modifiers
- •Using a Public Instance Variable
- •Creating an Instance of the Critter
- •Adding a Method
- •Creating the talk() Method for the CritterTalk Program
- •Changing the Menu to Use the talk() Method
- •Creating a Property in the CritterProp Program
- •Examining the Critter Prop Program
- •Creating the Critter with a Name Property
- •Using Properties as Filters
- •Making the Critter More Lifelike
- •Adding More Private Variables
- •Adding the Age() Method
- •Adding the Eat() Method
- •Adding the Play() Method
- •Modifying the Talk() Method
- •Making Changes in the Main Class
- •Summary
- •Introducing the Snowball Fight
- •Inheritance and Encapsulation
- •Creating a Constructor
- •Adding a Constructor to the Critter Class
- •Creating the CritViewer Class
- •Reviewing the Static Keyword
- •Calling a Constructor from the Main() Method
- •Working with Multiple Files
- •Overloading Constructors
- •Viewing the Improved Critter Class
- •Adding Polymorphism to Your Objects
- •Modifying the Critter Viewer in CritOver to Demonstrate Overloaded Constructors
- •Using Inheritance to Make New Classes
- •Creating a Class to View the Clone
- •Creating the Critter Class
- •Improving an Existing Class
- •Introducing the Glitter Critter
- •Adding Methods to a New Class
- •Changing the Critter Viewer Again
- •Creating the Snowball Fight
- •Building the Fighter
- •Building the Robot Fighter
- •Creating the Main Menu Class
- •Summary
- •Overview
- •Introducing the Visual Critter
- •Thinking Like a GUI Programmer
- •Creating a Graphical User Interface (GUI)
- •Examining the Code of a Windows Program
- •Adding New Namespaces
- •Creating the Form Object
- •Creating a Destructor
- •Creating the Components
- •Setting Component Properties
- •Setting Up the Form
- •Writing the Main() Method
- •Creating an Interactive Program
- •Responding to a Simple Event
- •Creating and Adding the Components
- •Adding an Event to the Program
- •Creating an Event Handler
- •Allowing for Multiple Selections
- •Choosing a Font with Selection Controls
- •Creating the User Interface
- •Examining Selection Tools
- •Creating Instance Variables in the Font Chooser
- •Writing the AssignFont() Method
- •Writing the Event Handlers
- •Working with Images and Scroll Bars
- •Setting Up the Picture Box
- •Adding a Scroll Bar
- •Revisiting the Visual Critter
- •Designing the Program
- •Determining the Necessary Tools
- •Designing the Form
- •Writing the Code
- •Summary
- •Chapter 7: Timers and Animation: The Lunar Lander
- •Introducing the Lunar Lander
- •Reading Values from the Keyboard
- •Introducing the Key Reader Program
- •Setting Up the Key Reader Program
- •Coding the KeyPress Event
- •Coding the KeyDown Event
- •Determining Which Key Was Pressed
- •Animating Images
- •Introducing the ImageList Control
- •Setting Up an Image List
- •Looking at the Image Collection
- •Displaying an Image from the Image List
- •Using a Timer to Automate Animation
- •Introducing the Timer Control
- •Configuring the Timer
- •Adding Motion
- •Checking for Keyboard Input
- •Working with the Location Property
- •Detecting Collisions between Objects
- •Coding the Crasher Program
- •Getting Values for newX and newY
- •Bouncing the Ball off the Sides
- •Checking for Collisions
- •Extracting a Rectangle from a Component
- •Getting More from the MessageBox Object
- •Introducing the MsgDemo Program
- •Retrieving Values from the MessageBox
- •Coding the Lunar Lander
- •The Visual Design
- •The Constructor
- •The timer1_Tick() Method
- •The moveShip() Method
- •The checkLanding() Method
- •The theForm_KeyDown() Method
- •The showStats() Method
- •The killShip() Method
- •The initGame() Method
- •Summary
- •Chapter 8: Arrays: The Soccer Game
- •The Soccer Game
- •Introducing Arrays
- •Exploring the Counter Program
- •Creating an Array of Strings
- •Referring to Elements in an Array
- •Working with Arrays
- •Using the Array Demo Program to Explore Arrays
- •Building the Languages Array
- •Sorting the Array
- •Designing the Soccer Game
- •Solving a Subset of the Problem
- •Adding Percentages for the Other Players
- •Setting Up the Shot Demo Program
- •Setting Up the List Boxes
- •Using a Custom Event Handler
- •Writing the changeStatus() Method
- •Kicking the Ball
- •Designing Programs by Hand
- •Examining the Form by Hand Program
- •Adding Components in the Constructor
- •Responding to the Button Event
- •Building the Soccer Program
- •Setting Up the Variables
- •Examining the Constructor
- •Setting Up the Players
- •Setting Up the Opponents
- •Setting Up the Goalies
- •Responding to Player Clicks
- •Handling Good Shots
- •Handling Bad Shots
- •Setting a New Current Player
- •Handling the Passage of Time
- •Updating the Score
- •Summary
- •Chapter 9: File Handling: The Adventure Kit
- •Introducing the Adventure Kit
- •Viewing the Main Screen
- •Loading an Adventure
- •Playing an Adventure
- •Creating an Adventure
- •Reading and Writing Text Files
- •Exploring the File IO Program
- •Importing the IO Namespace
- •Writing to a Stream
- •Reading from a Stream
- •Creating Menus
- •Exploring the Menu Demo Program
- •Adding a MainMenu Object
- •Adding a Submenu
- •Setting Up the Properties of Menu Items
- •Writing Event Code for Menus
- •Using Dialog Boxes to Enhance Your Programs
- •Exploring the Dialog Demo Program
- •Adding Standard Dialogs to Your Form
- •Using the File Dialog Controls
- •Responding to File Dialog Events
- •Using the Font Dialog Control
- •Using the Color Dialog Control
- •Storing Entire Objects with Serialization
- •Exploring the Serialization Demo Program
- •Creating the Contact Class
- •Referencing the Serializable Namespace
- •Storing a Class
- •Retrieving a Class
- •Returning to the Adventure Kit Program
- •Examining the Room Class
- •Creating the Dungeon Class
- •Writing the Game Class
- •Writing the Editor Class
- •Writing the MainForm Class
- •Summary
- •Chapter 10: Chapter Basic XML: The Quiz Maker
- •Introducing the Quiz Maker Game
- •Taking a Quiz
- •Creating and Editing Quizzes
- •Investigating XML
- •Defining XML
- •Creating an XML Document in .NET
- •Creating an XML Schema for Your Language
- •Investigating the .NET View of XML
- •Exploring the XmlNode Class
- •Exploring the XmlDocument Class
- •Reading an Existing XML Document
- •Creating the XML Viewer Program
- •Writing New Values to an XML Document
- •Building the Document Structure
- •Adding an Element to the Document
- •Displaying the XML Code
- •Examining the Quizzer Program
- •Building the Main Form
- •Writing the Quiz Form
- •Writing the Editor Form
- •Summary
- •Overview
- •Introducing the SpyMaster Program
- •Creating a Simple Database
- •Accessing the Data Server
- •Accessing the Data in a Program
- •Using Queries to Modify Data Results
- •Limiting Data with the SELECT Statement
- •Using an Existing Database
- •Adding the Capability to Display Queries
- •Creating a Visual Query Builder
- •Working with Relational Databases
- •Improving Your Data with Normalization
- •Using a Join to Connect Two Tables
- •Creating a View
- •Referring to a View in a Program
- •Incorporating the Agent Specialty Attribute
- •Working with Other Databases
- •Creating a New Connection
- •Converting a Data Set to XML
- •Reading from XML to a Data Source
- •Creating the SpyMaster Database
- •Building the Main Form
- •Editing the Assignments
- •Editing the Specialties
- •Viewing the Agents
- •Editing the Agent Data
- •Summary
- •List of Figures
- •List of Tables
- •List of Sidebars
picture box is a tall skinny rectangle, the image will appear to be taller and skinnier than usual. The Center setting causes the image to be displayed at its default size but centered within the image box, with the edges cropped out. The AutoSize setting causes the picture box to shrink or grow so that it is exactly the right size for the image.
Adding a Scroll Bar
Scroll bars are a wonderful innovation in interface design. Many times, you need some sort of integer input. If you ask a user to type in a number, you never know exactly what you will get. You usually have to do all sorts of error−detection gymnastics to ensure that the number is properly formatted and is not written out. Also, users generally prefer to use some sort of visual interface if they are in a GUI. The scroll bar control is designed to let the user visually enter a number. Much of the time, the user isn’t even aware that this is what he or she is doing, but that’s what scroll bars are for. The .NET framework supplies two scroll bar controls, but they are almost identical. The HScrollbar is aligned horizontally, and the VScrollbar is vertical. (Not surprisingly, both are inherited from a generic Scrollbar class.) The little box inside the scroll bar is sometimes called the elevator. The Value property of a scroll bar is an integer related to the position of the elevator. For horizontal scroll bars, smaller values are on the left. For vertical scroll bars, smaller values are at the top. You can set a range of values your scroll bar will return, with the Maximum and Minimum properties. Also, you can change how much the elevator moves when the user clicks the arrowheads, by setting the SmallChange property. You can indicate how far the elevator moves when the user clicks the shaft, by adjusting the LargeChange property. For the Sizer program, I chose a horizontal scroll bar with values between 50 and 200 because I want the image to vary between 50x50 and 200x200. I set the Minimum property to 50 and the Maximum property to 200. I left everything else alone.
Writing the Event−Handling Code
This program requires only one line of custom code, and that goes in the default event handler of the scroll bar. When the scroll bar is changed, the picture box’s size should also change to have the same height and width as the scroll bar’s value. Here’s the event code:
private void scrSize_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {
picCritter.Size = new Size(scrSize.Value, scrSize.Value);
}
The Scroll event occurs whenever the user moves the scroll bar. When this happens, the program changes the Size of picCritter. The Size property requires a size object (I learned that by looking at the object browser for the picture box). I looked up the size object and found that I could create it with two integers. Because I wanted the picture box to remain square, I just set the value of the scroll bar as both the X and Y values for the new size object.
Revisiting the Visual Critter
The Visual Critter program mentioned at the beginning of this chapter combines all the techniques you’ve learned throughout the chapter—and adds a few minor twists. The visual Critter is a picture box. The user changes the visual critter’s characteristics by manipulating the various controls on the screen.
161
Designing the Program
As a starting point, look at the sketch I used to design the program in Figure 6.24.
Figure 6.24: This sketch helped me to define how my program would be built.
Because the visual interface is so critical to GUI programs, the statement of the problem almost always involves at least one sketch of the user interface. (If you prefer not to sketch, your notes can be in English.) In visual programs, it’s a very good idea to figure out how the screen layout will be designed and determine the main types of objects you expect on the screen. In this type of sketch, I also like to name all my objects and write down any special characteristics of the objects. For example, you can see that I have predicted the range of the scroll bar and have indicated that several of the picture boxes will be invisible. The point of the sketch is not to solve all the programming problems. The goal is to make sure that you know what you’re trying to accomplish before you start writing code. Changing your ideas on paper is much easier than making changes after you start writing the program.
From the sketch, you can see that the program is centered around a picture box named picCritter. All the other elements on the form modify picCritter. I have decided to let the user change picCritter in four ways: The user can change the critter’s mood (which will change the image shown in picCritter) with a special form of the list box called the drop−down list box. The user can change the critter’s name by typing in a text box and clicking a button. The critter’s color can be modified by selecting a new color from a set of radio buttons, and the size is changed through a scroll bar. While I was sketching this out, it became clear that the number of controls on the form would be overwhelming, so I drew boxes around various elements to group the similar controls. For example, all the radio buttons are in a box, as are the text box and command button that deal with the critter’s name. I also added three special picture boxes that will be invisible to the user. I’ll explain soon what those are used for.
In the Real World
Many programmers design their programs first on chalkboards or whiteboards because these surfaces allow for even more flexibility than paper. A surprising number of my programs have been designed on napkins because a good idea came to me while I was at a restaurant. It doesn’t matter how you write your sketch (until you become a professional, when there will undoubtedly be standards), but you should do your initial work away from the programming environment. Resist the
162
temptation to design your form on−the−fly in the Designer. The .NET Designer will become confused if you change the design and layout too many times. It’s better to start the editor when you are clear about what you want your program to do.
Determining the Necessary Tools
Almost all the tools necessary for this project are described throughout this chapter, but my sketch pointed out the need for a couple variations.
A list box is a nice control but takes up a lot of room on the screen. What works better is the combo box, which is a form of the list box that expands when needed but takes up less room on the screen when the user is not using it. The combo box is a souped−up list box. It has all the same features as the traditional list box. Also, it can be set up so that the user can type in a value or set up as a list box with drop−down behavior. You set this behavior by modifying the comboBoxStyle property. A drop−down list box will be a nice addition to the program because it allows the user to pick from several options but doesn’t take up too much room on the screen.
In the Real World
Drop−down list boxes are popular with programmers because they allow many choices without taking as much space on the screen as check boxes, radio buttons, or traditional list boxes. Space is crucial when more items might be added to the list of choices. The other types of controls require space for new options. With a drop−down list, you can always add more elements to the list without requiring any more screen real estate. The other style of combo box is handy when you want to let the user type in a value or choose from a list.
The form has many controls on it, so breaking up the form into smaller segments is necessary. By digging around in the Toolbox, I found the panel control, which is perfect for this kind of thing.
I also needed to store the various images for the critter temporarily. I simply created extra picture boxes and set the visible property to false. The picture boxes are then invisible, but you can still copy the image property over to change the image of the picCritter picture box.
Designing the Form
After I figured out how the project should be laid out, I built the form. Figure 6.25 shows the form as it is being built in the Designer.
163
Figure 6.25: The form is easy to build if you have a sketch to follow.
I built the form by following the sketch. Notice that I added some panels to group the various types of controls and added a few labels to help the user understand what’s going on. I changed the panel’s border property to get the 3−D effect.
Trick When you use panels to separate controls, be sure to draw the panel first and then draw the control inside the panel. If you draw the control first, it will be attached to the form itself, rather than to the panel. If you draw the control inside the panel, you can move the panel, and all the controls will move with it. Also, you can use panels to isolate groups of radio buttons if you have more than one group of such controls on your form.
I also added one label above the critter image to handle displaying the critter’s name. In the original plan, I didn’t have a way for the critter to tell its name.
Writing the Code
In this type of program, most of your code consists of anticipating user actions and writing methods to handle events. All the events are the default events of the objects.
Adding Instance Variables
The Visual Critter program requires only one additional instance variable. I added myName as a string variable to hold the critter’s name. As usual, the instance variable goes inside the class definition line and before any method definitions.
Responding to a Change in the Combo Box
The combo box cboMood will fire off a SelectedIndexChanged event whenever the user chooses a new element from the combo box. If that happens, the program copies an image from one of the hidden image boxes.
164
private void cboMood_SelectedIndexChanged(object sender, System.EventArgs e) {
switch (cboMood.Text){ case "happy":
picCritter.Image = picHappy.Image; break;
case "indifferent":
picCritter.Image = picIndiff.Image; break;
case "mad":
picCritter.Image = picMad.Image; break;
default:
picCritter.Image = picIndiff.Image; break;
} // end switch
}// end cboMood event
The Text property of cboMood will contain whatever value is selected in the combo box. A switch statement examines all the possible values and copies the Image property of the appropriate invisible picture box to the image.
In the Real World
You can select and store images in several ways, but this is one of the simplest. Having the images already loaded in memory in hidden controls is preferable because loading an image from the disk drive can be a slow process. If the image is already in the computer’s memory (as it is when assigned to an invisible picture box), the image can be copied very quickly to the visible picture box.
Notice that I added a default clause, even though it should never happen. You should add a default clause to every switch statement because strange things happen and it’s better to be safe than sorry.
Clicking the Critter
When the user clicks the critter, it should say something. Here’s the code that occurs when the user clicks picCritter:
private void picCritter_Click(object sender, System.EventArgs e) {
if (myName == ""){
lblName.Text = "Please give me a name!";
}else {
lblName.Text = "My name is " + myName + "!"; MessageBox.Show("Hi, my name is " + myName);
}// end if
}// end picCritter click
If the myName variable hasn’t been changed by typing a new name in the text box, the critter asks the user to supply a name. Otherwise, the program copies a friendly message to the lblName label. Notice the line that starts with MessageBox. The message box object is a convenient way to send a quick message to the user. Use the MessageBox.Show() method to say something in a little dialog box.
165
Trap The MessageBox.Show() method is very handy but interferes with the flow of the program. Also, if you use it too much, your users will be annoyed. Integrating all your output into the form (when you can) is much more in the spirit of GUI programming. Also, if you’re familiar with programming in Visual Basic or JavaScript, you might wonder where the equivalent to inputbox or prompt is in C#. The .NET framework does not supply a quick dialog for input.
You have to make your own if you want one. Generally, though, you can get all the input you need from your programs.
Changing the Critter’s Name
The txtName text box and the btnName command button work together to let the user change the critter’s name. You might be surprised that no code is attached to the text box. All the code for name changing happens in the command button. Here is the code:
private void btnName_Click(object sender, System.EventArgs e) {
if (txtName.Text == ""){ MessageBox.Show
("Please enter a name in the text box and click the button again");
}else {
myName = txtName.Text;
MessageBox.Show("OK, You changed my name.");
}// end if
}// end btnName click
This method ensures that there is a name in the text box. Then it copies that name to the myName variable and lets the user know that the name has been changed.
Changing the Critter’s Color
The critter’s color is changed through the radio buttons. The code is very straightforward:
private void radRed_CheckedChanged(object sender, System.EventArgs e) {
picCritter.BackColor = Color.Red; } // end radRed event
private void radGreen_CheckedChanged(object sender, System.EventArgs e) {
picCritter.BackColor = Color.Green; } // end radGreen event
private void radBlue_CheckedChanged(object sender, System.EventArgs e) {
picCritter.BackColor = Color.Blue; } // end radBlue event
Each of the radio buttons immediately changes the background color of picCritter to the appropriate color. Notice that all the legal color values are available in the System.Drawing namespace. If you type Color. while this namespace is available, you see a complete list of color names you can use.
Changing the Critter’s Size
The Critter’s size is changed by a scroll bar. In fact, I stole the code directly from the Sizer program featured earlier in this chapter.
166