- •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
Figure 11.10: Agents table after I’ve entered a few of my agents. (This page will self−destruct in 5 seconds…)
Keeping Track of Your Data Structure
The way the server explorer displays the structure of your database in the IDE is a welcome addition. You used to be able to tell which programmers were working on databases because they always had paper diagrams of their data structure tacked to all the walls in their cubicle. (Many pros still do this.) In fact, there are stories of data programmers taking only their data diagrams as they left a burning building. The problem with paper diagrams is they have to be replaced every time the data structure is changed. The server explorer gives you an easy way to see exactly what tables are in your database, and what fields belong to each table. This seems like trivial information to keep track of right now, but the complexity of databases seems to grow very quickly.
Accessing the Data in a Program
Now the spy data is available to my server, but it isn’t very interesting there. I want to be able to use the data in programs to save the world for democracy, apple pie, and quarter video arcades. It shouldn’t surprise you that the IDE makes it easy to integrate a database with a program. Once you’ve created a database on your server, you can easily access it from any programs written on that same machine (later on I’ll show you how to get to other databases, too). To illustrate this, create a project (or simply go to a form if you’re already in a project). C# has a special control designed explicitly for working with databases. It’s called the Data Grid control. To use it, display a form in the visual designer, and go back to the traditional toolbox (with all the form components you’re used to placing on the screen). The data grid can be dropped on the form like any other control. It is not very interesting unless it is connected with some form of database. To begin creating the data connection, drag the Agents table from the server connection onto your form. Figure 11.11 illustrates the visual designer after I have added a data grid control and dragged the Agents table to the form.
326
Figure 11.11: When you drag a table to your form, two new objects are created in the non−visible segment of your form.
Dragging a table to the form causes the IDE to create two objects. A SqlConnection object describes the connection between your program and the database. There are other kinds of connection objects, but they all do basically the same thing. A connection object encapsulates the actual connection. If you want to connect to a database on a remote system, you can set up the connection object to point to the remote machine, handle any logins, and start the connection.
The most critical property of the SqlConnection is the ConnectionString property. Take a look at it in the designer; it’s a big ugly string variable designed to specify how to connect to the database. It’s usually easiest to let the designer automatically generate an SqlConnection object, (and the complicated ConnectionnString property) and then modify it as needed.
The other object that is automatically created when you drag a table to the screen is an instance of SqlDataAdapter. The adapter classes are a new feature of the .NET data access scheme. In a nutshell, a data adapter automatically generates a local copy of a database on the client’s computer, and manages the relationship between the local copy of the database and the original database. This separation is especially useful when you are working on databases across Internet connections, but it works just as well when the database is local. You’ll generally work with the SqlDataAdapter’s Fill() method when you want to request data from the main database, and the Update() method when you want to update the main database from your local version.
Creating a DataSet Object
Although the SqlConnection and SqlDataAdapter are handy, you need one more data class to work directly with data in your forms. This important class is called the DataSet class. Each database uses a custom extension of the DataSet class to provide access to the database. Fortunately, .NET makes it easy to generate an appropriate DataSet from a data adapter. To create the new DataSet, look at the properties box of the DataAdapter class. At the bottom of the properties box, you see links for some special commands. Choose Preview Data, and you see the dialog box featured in Figure 11.12.
327
Figure 11.12: The Preview Data dialog illustrates how the data looks to the program.
How Do Data Connections, Data Adapters, and Data Sets Fit Together?
All this new (and similar) terminology can be baffling. It actually makes sense if you understand how Microsoft’s underlying data model (called ADO.NET) works. Essentially, your programs are considered completely separated from your actual database, even if they are on the same machine. In the .NET model, databases and programs have the same kind of long−distance relationship that Web browsers have with Web servers. In the Web, a browser requests a page, and that page is loaded onto the local machine. The ADO.NET data model works in a very similar way. Think of the DataConnection object as being your placeholder for the actual (remote) database. The DataSet object holds a local copy of the data. You can manipulate the DataSet object all you want, but it doesn’t directly affect the original database. The DataAdapter class is the conduit between the (remote) DataConnection and the (local) DataSet. The DataAdapter reminds me of the pneumatic tubes sometimes used at bank drive−through windows to send checks and pens from the bank to the cars. It is a communication medium. You use methods of the DataAdapter to fill up the DataSet with data from the DataConnection, and you use other methods of DataAdapter to update the original database from the local DataSet. If you’re still confused, read on. You’ll get it after a little more exposure.
The Preview Dialog creates a temporary DataSet based on a particular data adapter. Because the
328
current program has only one data adapter available, clicking on the Fill DataSet button creates the temporary data set based on the current data adapter, and displays the results in the dialog, as illustrated in Figure 11.13.
Figure 11.13: After pressing the Fill DataSet button, the data set appears on the dialog.
Once you have confirmed that the database acts as you expect, close the Preview Data dialog and look again at the bottom of the Properties Window for the Generate DataSet command. Click on this link to get the Generate DataSet dialog, shown in Figure 11.14.
329
Figure 11.14: The Generate DataSet Dialog prompts you to name your new DataSet.
To create a new DataSet, choose the New radio button, then type in the name of your new data set class.
Trap When you created the connection and adapter classes, you were making instances of existing classes. The data set is different, because you are creating an entirely new class that extends the base DataSet class. The Generate DataSet dialog creates both the new data set class and an instance of that class. That’s why when you leave the dialog, the data set object at the bottom of your form has a one at the end (the default name for any instance of a class is the class name followed by an integer). If you do not rename the data set, it is called DataSet1, and its first instance is called DataSet11. I was quite confused by this until I followed my own advice from way back in Chapter 1, "Basic Input and Output: A Mini Adventure." When you make new things, you should rename them. As you can see in Figure 11.14. I called my data set theData.
Once you leave the Generate DataSet dialog, you are returned to your form and a new instance of your data set appears at the bottom of the form near the connection and adapter objects. Because I named my data set theData, the default name for the new data set is theData1. I renamed the instance myDS, to help me remember this is my custom data set.
330
Connecting the Data Set to the Grid
The data grid control is designed to be bound to a data set. This allows an automatic connection between the grid and the data set. To bind myDS to the data grid, set the DataSource property of the grid to myDS, and the DataMember property to Agents. Both properties generate drop−down list boxes if the data source has been connected properly. Figure 11.15 illustrates setting up a data grid.
Figure 11.15: Setting the data DataMember property only works after you’ve set the DataSource property.
The DataSource property determines what DataSet object the grid will be connected to. DataSets can (and will, later in this chapter) have more than one table, so the DataMembers property is used to determine which table (or other entity) is connected to the grid.
Filling the DataSet from the Adapter
The database is almost ready. Figure 11.16 shows the data grid with its DataSource and DataMember properties set appropriately.
331
Figure 11.16: The program is almost ready, but the actual data has not yet been passed to the data set from the original database.
The only thing left to do is fill up the data set. Recall that the data set is simply a local copy of the database. The DataAdapter handles the connection between the original database and the copy stored in the data set. I added one line of code to the form’s load method to fill up the data set.
private void SimpleSpyForm_Load(object sender, System.EventArgs e) {
myAdapter.Fill(myDS); } // end form load
The adapter’s Fill() method requires a data set as a parameter. It goes to the original database and grabs the relevant information (determined by the properties of the adapter class) to populate the data set.
You can now run the Simple Spy program to get the results shown in Figure 11.17.
332