You are previewing Head First C#, 2nd Edition.

Head First C#, 2nd Edition

Cover of Head First C#, 2nd Edition by Andrew Stellman... Published by O'Reilly Media, Inc.
  1. Head First C#
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Advance Praise for Head First C#
  5. Praise for other Head First books
  7. How to Use this Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking
    3. And we know what your brain is thinking
    4. Metacognition: thinking about thinking
    5. Here’s what WE did
    6. Here’s what YOU can do to bend your brain into submission
    7. What you need for this book
    8. Read me
    9. The technical review team
    10. Acknowledgments
    11. Safari® Books Online
  8. 1. Get Productive with C#: Visual Applications, in 10 minutes or less
    1. Why you should learn C#
      1. Here’s what the IDE automates for you...
      2. What you get with Visual Studio and C#...
    2. C# and the Visual Studio IDE make lots of things easy
    3. Help the CEO go paperless
    4. Get to know your users’ needs before you start building your program
    5. Here’s what you’re going to build
    6. What you do in Visual Studio...
    7. What Visual Studio does for you...
    8. Develop the user interface
    9. Visual Studio, behind the scenes
    10. Add to the auto-generated code
    11. You can already run your application
    12. Where are my files?
    13. Here’s what we’ve done so far
      1. .NET Visual Objects
    14. We need a database to store our information
    15. The IDE created a database
    16. SQL is its own language
    17. Creating the table for the Contact List
    18. The blanks on the contact card are columns in our People table
    19. Finish building the table
    20. Insert your card data into the database
    21. Connect your form to your database objects with a data source
    22. Add database-driven controls to your form
    23. Good programs are intuitive to use
    24. Test drive
      1. The IDE builds first, then runs
    25. How to turn YOUR application into EVERYONE’S application
    26. Give your users the application
    27. You’re NOT done: test your installation
    28. You’ve built a complete data-driven application
  9. 2. It’s All Just Code: Under the hood
    1. When you’re doing this...
    2. ...the IDE does this
    3. Where programs come from
      1. Every program starts out as source code files
      2. The .NET Framework gives you the right tools for the job
      3. Build the program to create an executable
      4. Your program runs inside the CLR
    4. The IDE helps you code
    5. When you change things in the IDE, you’re also changing your code
      1. Wait, wait! What did that say?
    6. Anatomy of a program
      1. Let’s take a closer look at your code
    7. Your program knows where to start
    8. You can change your program’s entry point
      1. So what happened?
    9. Two classes can be in the same namespace
    10. Your programs use variables to work with data
      1. Declare your variables
      2. Variables vary
      3. You have to assign values to variables before you use them
      4. A few useful types
    11. C# uses familiar math symbols
    12. Use the debugger to see your variables change
    13. Loops perform an action over and over
      1. Use a code snippet to write simple for loops
    14. Time to start coding
      1. Add statements to show a message
    15. if/else statements make decisions
    16. Set up conditions and see if they’re true
      1. Use logical operators to check conditions
      2. Set a variable and then check its value
      3. Add another conditional test
      4. Add loops to your program
  10. 3. Objects: Get Oriented!: Making code make sense
    1. How Mike thinks about his problems
    2. How Mike’s car navigation system thinks about his problems
    3. Mike’s Navigator class has methods to set and modify routes
      1. Some methods have a return value
    4. Use what you’ve learned to build a program that uses a class
      1. So what did you just build?
    5. Mike gets an idea
      1. He could create three different Navigator classes...
    6. Mike can use objects to solve his problem
    7. You use a class to build an object
      1. An object gets its methods from its class
    8. When you create a new object from a class, it’s called an instance of that class
    9. A better solution...brought to you by objects!
      1. Theory and practice
      2. A little advice for the code exercises
    10. An instance uses fields to keep track of things
      1. Methods are what an object does. Fields are what the object knows
    11. Let’s create some instances!
    12. Thanks for the memory
      1. Let’s take a closer look at what happened here
    13. What’s on your program’s mind
    14. You can use class and method names to make your code intuitive
    15. Give your classes a natural structure
      1. Let’s build a class diagram
    16. Class diagrams help you organize your classes so they make sense
    17. Build a class to work with some guys
    18. Create a project for your guys
    19. Build a form to interact with the guys
    20. There’s an easier way to initialize objects
  11. 4. Types and References: It’s 10:00. Do you know where your data is?
    1. The variable’s type determines what kind of data it can store
    2. A variable is like a data to-go cup
    3. 10 pounds of data in a 5 pound bag
    4. Even when a number is the right size, you can’t just assign it to any variable
      1. So what happened?
    5. When you cast a value that’s too big, C# will adjust it automatically
    6. C# does some casting automatically
    7. When you call a method, the arguments must be compatible with the types of the parameters
    8. Combining = with an operator
    9. Objects use variables, too
    10. Refer to your objects with reference variables
    11. References are like labels for your object
    12. If there aren’t any more references, your object gets garbage-collected
    13. Multiple references and their side effects
    14. Two references means TWO ways to change an object’s data
    15. A special case: arrays
      1. Use each element in an array like it is a normal variable
    16. Arrays can contain a bunch of reference variables, too
    17. Welcome to Sloppy Joe’s Budget House o’ Discount Sandwiches!
    18. Objects use references to talk to each other
    19. Where no object has gone before
    20. Build a typing game
  12. I. C# Lab: A Day at the Races
    1. 5. Encapsulation: Keep your privates... private
      1. Kathleen is an event planner
      2. What does the estimator do?
      3. Kathleen’s Test Drive
      4. Each option should be calculated individually
      5. It’s easy to accidentally misuse your objects
      6. Encapsulation means keeping some of the data in a class private
      7. Use encapsulation to control access to your class’s methods and fields
      8. But is the realName field REALLY protected?
      9. Private fields and methods can only be accessed from inside the class
      10. Encapsulation keeps your data pristine
      11. Properties make encapsulation easier
      12. Build an application to test the Farmer class
      13. Use automatic properties to finish the class
      14. What if we want to change the feed multiplier?
      15. Use a constructor to initialize private fields
    2. 6. Inheritance: Your object’s family tree
      1. Kathleen does birthday parties, too
      2. We need a BirthdayParty class
      3. Build the Party Planner version 2.0
      4. One more thing...can you add a $100 fee for parties over 12?
      5. When your classes use inheritance, you only need to write your code once
      6. Build up your class model by starting general and getting more specific
      7. How would you design a zoo simulator?
      8. Use inheritance to avoid duplicate code in subclasses
      9. Different animals make different noises
      10. Think about how to group the animals
      11. Create the class hierarchy
      12. Every subclass extends its base class
      13. Use a colon to inherit from a base class
      14. We know that inheritance adds the base class fields, properties, and methods to the subclass...
      15. A subclass can override methods to change or replace methods it inherited
      16. Any place where you can use a base class, you can use one of its subclasses instead
      17. A subclass can hide methods in the superclass
      18. Use the override and virtual keywords to inherit behavior
      19. A subclass can access its base class using the base keyword
      20. When a base class has a constructor, your subclass needs one, too
      21. Now you’re ready to finish the job for Kathleen!
      22. Build a beehive management system
      23. First you’ll build the basic system
      24. Use inheritance to extend the bee management system
    3. 7. Interfaces and Abstract Classes: Making classes keep their promises
      1. Let’s get back to bee-sics
      2. We can use inheritance to create classes for different types of bees
      3. An interface tells a class that it must implement certain methods and properties
      4. Use the interface keyword to define an interface
      5. Now you can create an instance of NectarStinger that does both jobs
      6. Classes that implement interfaces have to include ALL of the interface’s methods
      7. Get a little practice using interfaces
      8. You can’t instantiate an interface, but you can reference an interface
      9. Interface references work just like object references
      10. You can find out if a class implements a certain interface with “is”
      11. Interfaces can inherit from other interfaces
      12. The RoboBee 4000 can do a worker bee’s job without using valuable honey
      13. is tells you what an object implements, as tells the compiler how to treat your object
      14. A CoffeeMaker is also an Appliance
      15. Upcasting works with both objects and interfaces
      16. Downcasting lets you turn your appliance back into a coffee maker
      17. Upcasting and downcasting work with interfaces, too
      18. There’s more than just public and private
      19. Access modifiers change visibility
      20. Some classes should never be instantiated
      21. An abstract class is like a cross between a class and an interface
      22. Like we said, some classes should never be instantiated
      23. An abstract method doesn’t have a body
      24. Polymorphism means that one object can take many different forms
    4. 8. Enums and Collections; Storing lots of data
      1. Strings don’t always work for storing categories of data
      2. Enums let you work with a set of valid values
      3. Enums let you represent numbers with names
      4. We could use an array to create a deck of cards...
      5. Arrays are hard to work with
      6. Lists make it easy to store collections of...anything
      7. Lists are more flexible than arrays
      8. Lists shrink and grow dynamically
      9. Generics can store any type
      10. Collection initializers work just like object initializers
      11. Let’s create a List of Ducks
      12. Lists are easy, but SORTING can be tricky
      13. IComparable<Duck> helps your list sort its ducks
      14. Use IComparer to tell your List how to sort
      15. Create an instance of your comparer object
      16. IComparer can do complex comparisons
      17. Overriding a ToString() method lets an object describe itself
      18. Update your foreach loops to let your Ducks and Cards print themselves
      19. You can upcast an entire list using IEnumerable
      20. You can build your own overloaded methods
      21. Use a dictionary to store keys and values
      22. The Dictionary Functionality Rundown
      23. Build a program that uses a Dictionary
      24. And yet MORE collection types...
      25. A queue is FIFO—First In, First Out
      26. A stack is LIFO—Last In, First Out
  13. II. C# Lab: The Quest
    1. 9. Reading and Writing Files: Save the byte array, save the world
      1. .NET uses streams to read and write data
      2. Different streams read and write different things
      3. A FileStream reads and writes bytes to a file
      4. How to write text to a file in 3 simple steps
      5. The Swindler launches another diabolical plan
      6. Reading and writing using two objects
      7. Data can go through more than one stream
      8. Use built-in objects to pop up standard dialog boxes
      9. Dialog boxes are just another .NET control
      10. Dialog boxes are objects, too
      11. Use the built-in File and Directory classes to work with files and directories
      12. Use file dialogs to open and save files (all with just a few lines of code)
      13. IDisposable makes sure your objects are disposed of properly
      14. Avoid file system errors with using statements
      15. Trouble at work
      16. Writing files usually involves making a lot of decisions
      17. Use a switch statement to choose the right option
      18. Use a switch statement to let your deck of cards read from a file or write itself out to one
      19. Add an overloaded Deck() constructor that reads a deck of cards in from a file
      20. What happens to an object when it’s serialized?
      21. But what exactly IS an object’s state? What needs to be saved?
      22. When an object is serialized, all of the objects it refers to get serialized, too...
      23. Serialization lets you read or write a whole object all at once
      24. If you want your class to be serializable, mark it with the [Serializable] attribute
      25. Let’s serialize and deserialize a deck of cards
      26. .NET uses Unicode to store characters and text
      27. C# can use byte arrays to move data around
      28. Use a BinaryWriter to write binary data
      29. You can read and write serialized files manually, too
      30. Find where the files differ, and use that information to alter them
      31. Working with binary files can be tricky
      32. Use file streams to build a hex dumper
      33. StreamReader and StreamWriter will do just fine (for now)
      34. Use Stream.Read() to read bytes from a stream
    2. 10. Exception Handling: Putting out fires gets old
      1. Brian needs his excuses to be mobile
      2. When your program throws an exception, .NET generates an Exception object
      3. Brian’s code did something unexpected
      4. All exception objects inherit from Exception
      5. The debugger helps you track down and prevent exceptions in your code
      6. Use the IDE’s debugger to ferret out exactly what went wrong in the Excuse Manager
      7. Uh oh—the code’s still got problems...
      8. Handle exceptions with try and catch
      9. What happens when a method you want to call is risky?
      10. Use the debugger to follow the try/catch flow
      11. If you have code that ALWAYS should run, use a finally block
      12. Use the Exception object to get information about the problem
      13. Use more than one catch block to handle multiple types of exceptions
      14. One class throws an exception, another class catches the exception
      15. Bees need an OutOfHoney exception
      16. An easy way to avoid a lot of problems: using gives you try and finally for free
      17. Exception avoidance: implement IDisposable to do your own cleanup
      18. The worst catch block EVER: catch-all plus comments
      19. Temporary solutions are OK (temporarily)
      20. A few simple ideas for exception handling
      21. Brian finally gets his vacation...
    3. 11. Events and Delegates: What your code does when you’re not looking
      1. Ever wish your objects could think for themselves?
      2. But how does an object KNOW to respond?
      3. When an EVENT occurs...objects listen
      4. One object raises its event, others listen for it...
      5. Then, the other objects handle the event
      6. Connecting the dots
      7. The IDE creates event handlers for you automatically
      8. Generic EventHandlers let you define your own event types
      9. The forms you’ve been building all use events
      10. One event, multiple handlers
      11. Connecting event senders with event receivers
      12. A delegate STANDS IN for an actual method
      13. Delegates in action
      14. An object can subscribe to an event...
      15. Use a callback to control who’s listening
      16. A callback is just a way to use delegates
    4. 12. Review and Preview: Knowledge, power, and building cool stuff
      1. You’ve come a long way, baby
      2. We’ve also become beekeepers
      3. The beehive simulator architecture
      4. Building the beehive simulator
      5. Life and death of a flower
      6. Now we need a Bee class
      7. P. A. H. B. (Programmers Against Homeless Bees)
      8. The hive runs on honey
      9. Filling out the Hive class
      10. The hive’s Go() method
      11. We’re ready for the World
      12. We’re building a turn-based system
      13. Here’s the code for World
      14. Giving the bees behavior
      15. The main form tells the world to Go()
      16. We can use World to get statistics
      17. Timers fire events over and over again
      18. The timer’s using an event handler behind the scenes
      19. Add a timer to the simulator
      20. Test drive
      21. Let’s work with groups of bees
      22. A collection collects...DATA
      23. LINQ makes working with data in collections and databases easy
      24. Test drive (Part 2)
      25. One final challenge: Open and Save
    5. 13. Controls and Graphics: Make it pretty
      1. You’ve been using controls all along to interact with your programs
      2. Form controls are just objects
      3. Use controls to animate the beehive simulator
      4. Add a renderer to your architecture
      5. The renderer draws everything in the world on the two forms
      6. Controls are well suited for visual display elements
      7. Build your first animated control
      8. BeeControl is LIKE a let’s start by INHERITING from PictureBox
      9. Create a button to add the BeeControl to your form
      10. Your controls need to dispose their controls, too!
      11. A UserControl is an easy way to build a control
      12. Your simulator’s renderer will use your BeeControl to draw animated bees on your forms
      13. Add the hive and field forms to the project
      14. Build the renderer
      15. Now connect the main form to your two new forms, HiveForm and FieldForm
      16. Test
      17. Looks great, but something’s not quite right...
      18. Let’s take a closer look at those performance issues
      19. You resized your Bitmaps using a Graphics object
      20. Your image resources are stored in Bitmap objects
      21. Use System.Drawing to TAKE CONTROL of graphics yourself
      22. A 30-second tour of GDI+ graphics
      23. Use graphics to draw a picture on a form
      24. Graphics can fix our transparency problem...
      25. Use the Paint event to make your graphics stick
      26. A closer look at how forms and controls repaint themselves
      27. Double buffering makes animation look a lot smoother
      28. Double buffering is built into forms and controls
      29. Use a Graphics object and an event handler for printing
      30. PrintDocument works with the print dialog and print preview window objects
    6. 14. Captain Amazing: The Death of the Object
      1. Your last chance to DO something... your object’s finalizer
      2. When EXACTLY does a finalizer run?
      3. Dispose() works with using, finalizers work with garbage collection
      4. Finalizers can’t depend on stability
      5. Make an object serialize itself in its Dispose()
      6. A struct looks like an object...
      7. ...but isn’t an object
      8. Values get copied; references get assigned
      9. Structs are value types; objects are reference types
      10. The stack vs. the heap: more on memory
      11. Use out parameters to make a method return more than one value
      12. Pass by reference using the ref modifier
      13. Use optional parameters to set default values
      14. Use nullable types when you need nonexistent values
      15. Nullable types help you make your programs more robust
      16. Captain Amazing...not so much
      17. Extension methods add new behavior to EXISTING classes
      18. Extending a fundamental type: string
    7. 15. LINQ: Get control of your data
      1. An easy project...
      2. ...but the data’s all over the place
      3. LINQ can pull data from multiple sources
      4. .NET collections are already set up for LINQ
      5. LINQ makes queries easy
      6. LINQ is simple, but your queries don’t have to be
      7. LINQ is versatile
      8. LINQ can combine your results into groups
      9. Combine Jimmy’s values into groups
      10. Use join to combine two collections into one query
      11. Jimmy saved a bunch of dough
      12. Connect LINQ to a SQL database
      13. Use a join query to connect Starbuzz and Objectville
  14. III. C# Lab: Invaders
    1. A. Leftovers: The top 11 things we wanted to include in this book
      1. #1. The Basics
      2. #2. Namespaces and assemblies
      3. #3. Use BackgroundWorker to make your UI responsive
      4. #4. The Type class and GetType()
      5. #5. Equality, IEquatable, and Equals()
      6. #6. Using yield return to create enumerable objects
      7. #7. Refactoring
      8. #8. Anonymous types, anonymous methods, and lambda expressions
      9. #9. Serializing data using DataContractSerializer
      10. #10. LINQ to XML
      11. #11. Windows Presentation Foundation
      12. Did you know that C# and the .NET Framework can...
  15. Index
  16. About the Authors
  17. Copyright
O'Reilly logo

Chapter 1. Get Productive with C#: Visual Applications, in 10 minutes or less

image with no caption

Want to build great programs really fast?

With C#, you’ve got a powerful programming language and a valuable tool at your fingertips. With the Visual Studio IDE, you’ll never have to spend hours writing obscure code to get a button working again. Even better, you’ll be able to focus on getting your work done, rather than remembering which method parameter was for the name of a button, and which one was for its label. Sound appealing? Turn the page, and let’s get programming.

Why you should learn C#

C# and the Visual Studio IDE make it easy for you to get to the business of writing code, and writing it fast. When you’re working with C#, the IDE is your best friend and constant companion.


The IDE—or Visual Studio Integrated Development Environment—is an important part of working in C#. It’s a program that helps you edit your code, manage your files, and publish your projects.

Here’s what the IDE automates for you...

Every time you want to get started writing a program, or just putting a button on a form, your program needs a whole bunch of repetitive code.

image with no caption

What you get with Visual Studio and C#...

With a language like C#, tuned for Windows programming, and the Visual Studio IDE, you can focus on what your program is supposed to do immediately:

image with no caption

C# and the Visual Studio IDE make lots of things easy

When you use C# and Visual Studio, you get all of these great features, without having to do any extra work. Together, they let you:

  1. Build an application, FAST. Creating programs in C# is a snap. The language is powerful and easy to learn, and the Visual Studio IDE does a lot of work for you automatically. You can leave mundane coding tasks to the IDE and focus on what your code should accomplish.

  2. Design a great looking user interface. The Form Designer in the Visual Studio IDE is one of the easiest design tools to use out there. It does so much for you that you’ll find that making stunning user interfaces is one of the most satisfying parts of developing a C# application. You can build full-featured professional programs without having to spend hours writing a graphical user interface entirely from scratch.

  3. Create and interact with databases. The IDE includes an easy-to-use interface for building databases, and integrates seamlessly with SQL Server Compact Edition and many other popular database systems.

  4. Focus on solving your REAL problems. The IDE does a lot for you, but you are still in control of what you build with C#. The IDE just lets you focus on your program, your work (or fun!), and your customers. But the IDE handles all the grunt work, such as:

    • Keeping track of all your projects

    • Making it easy to edit your project’s code

    • Keeping track of your project’s graphics, audio, icons, and other resources

    • Managing and interacting with databases

    All this means you’ll have all the time you would’ve spent doing this routine programming to put into building killer programs.


    You’re going to see exactly what we mean next.

Help the CEO go paperless

The Objectville Paper Company just hired a new CEO. He loves hiking, coffee, and nature...and he’s decided that to help save forests, he wants to become a paperless executive, starting with his contacts. He’s heading to Aspen to go skiing for the weekend, and expects a new address book program by the time he gets back. won’t be just the old CEO who’s looking for a job.

image with no caption

Get to know your users’ needs before you start building your program

Before we can start writing the address book application—or any application—we need to take a minute and think about who’s going to be using it, and what they need from the application.

  1. The CEO needs to be able to run his address book program at work and on his laptop, too. He’ll need an installer to make sure that all of the right files get onto each machine.

    image with no caption

    Think about your users and their needs before you start building the code, and they’ll be happy with the final product once you’re done!

  2. The Objectville Paper Company sales team wants to access his address book, too. They can use his data to build mailing lists and get client leads for more paper sales.

    The CEO figures a database would be the best way for everyone in the company to see his data, and then he can just keep up with one copy of all his contacts.

    image with no caption

Here’s what you’re going to build

You’re going to need an application with a graphical user interface, objects to talk to a database, the database itself, and an installer. It sounds like a lot of work, but you’ll build all of this over the next few pages.

Here’s the structure of the program we’re going to create:

image with no caption

What you do in Visual Studio...

Go ahead and start up Visual Studio, if you haven’t already. Skip over the start page and select New Project from the File menu. Name your project “Contacts” and click OK. There are several project types to choose from. Select Windows Forms Application and choose “Contacts” as the name for your new project.

image with no caption

Watch it!

Things may look a bit different in your IDE.

This is what the “New Project” window looks like in Visual Studio 2010 Express Edition. If you’re using the Professional or Team Foundation edition, it might be a bit different. But don’t worry, everything still works exactly the same.

What Visual Studio does for you...


Make sure that you save your project as soon as you create it by selecting “Save All” from the File menu—that’ll save all of the project files out to the folder. If you select “Save”, it just saves the one you’re working on.

As soon as you save the project, the IDE creates Form1.cs, Form1.Designer.cs, and Program.cs file, when you create a new project. It adds these to the Solution Explorer window, and by default, puts those files in My Documents\Visual Studio 2010\Projects\Contacts\.

image with no caption

Visual Studio will generate code you can use as a starting point for your applications.

Making sure the application does what it’s supposed to do is entirely up to you.

Develop the user interface

Adding controls and polishing the user interface is as easy as dragging and dropping with the Visual Studio IDE. Let’s add a logo to the form:

  1. Use the PictureBox control to add a picture.

    Click on the PictureBox control in the Toolbox, and drag it onto your form. In the background, the IDE added code to Form1.Designer.cs for a new picture control.

    image with no caption


    It’s OK if you’re not a pro at user interface design.

    We’ll talk a lot more about designing good user interfaces later on. For now, just get the logo and other controls on your form, and worry about behavior. We’ll add some style later.

    image with no caption
  2. Set the PictureBox to Zoom mode.

    Every control on your form has properties that you can set. Click the little black arrow for a control to access these properties. Change the PictureBox’s Size property to “Zoom” to see how this works:


    You can also use the “Properties” window in the IDE to set the Size property. The little black arrow is just there to make it easy to access the most common properties of any control.

    image with no caption
  3. Download the Objectville Paper Company logo.

    Download the Objectville Paper Co. logo from Head First Labs ( and save it to your hard drive. Then click the PictureBox properties arrow, and select Choose Image. You’ll see a Select Resources window pop up. Click the “Local Resource” radio button to enable the “Import...” button at the top of the form. Click that button, find your logo, and you’re all set.

    image with no caption

Visual Studio, behind the scenes

Every time you do something in the Visual Studio IDE, the IDE is writing code for you. When you created the logo and told Visual Studio to use the image you downloaded, Visual Studio created a resource and associated it with your application. A resource is any graphics file, audio file, icon, or other kind of data file that gets bundled with your application. The graphics file gets integrated into the program, so that when it’s installed on another computer, the graphic is installed along with it and the PictureBox can use it.

When you dragged the PictureBox control onto your form, the IDE automatically created a resource file called Form1.resx to store that resource and keep it in the project. Double-click on this file, and you’ll be able to see the newly imported image.

image with no caption

Go to the Solution Explorer and click on the “expand” icon next to Form1.cs to expand it (if it’s not already expanded). This will display two files: Form1.Designer.cs and Form1.resx. Double-click on Form1.resx, click on the arrow next to “Strings”, and select “Images” from the drop-down list (or hit Ctrl-2) to see the logo that you imported. That file is what links it to the PictureBox, and the IDE added code to do the linking.

image with no caption

Add to the auto-generated code

The IDE creates lots of code for you, but you’ll still want to get into this code and add to it. Let’s set the logo up to show an About message when the users run the program and click on the logo.

When you’re editing a form in the IDE, double-clicking on any of the toolbox controls causes the IDE to automatically add code to your project. Make sure you’ve got the form showing in the IDE, and then double-click on the PictureBox control. The IDE will add code to your project that gets run any time a user clicks on the PictureBox. You should see some code pop up that looks like this:

image with no caption

You can already run your application

Press the F5 key on your keyboard, or click the green arrow button () on the toolbar to check out what you’ve done so far. (This is called “debugging,” which just means running your program using the IDE.) You can stop debugging by selecting “Stop Debugging” from the Debug menu or clicking this toolbar button: .

image with no caption

Where are my files?

When you run your program, Visual Studio copies your files to My Documents\Visual Studio 2010\Projects\Contacts\Contacts\bin\debug. You can even hop over to that directory and run your program by double-clicking on the .exe file the IDE creates.


This isn’t a mistake; there are two levels of folders. The inner folder has the actual C# code files.

image with no caption

Here’s what we’ve done so far

We’ve built a form and created a PictureBox object that pops up a message box when it’s clicked on. Next, we need to add all the other fields from the card, like the contact’s name and phone number.

Let’s store that information in a database. Visual Studio can connect fields directly to that database for us, which means we don’t have to mess with lots of database access code (which is good). But for that to work, we need to create our database so that the controls on the form can hook up to it. So we’re going to jump from the .NET Visual Objects straight to the Data Storage section.

.NET Visual Objects

image with no caption

Visual Studio can generate code to connect your form to a database, but you need to have the database in place BEFORE generating that code.

We need a database to store our information

Before we add the rest of the fields to the form, we need to create a database to hook the form up to. The IDE can create lots of the code for connecting our form to our data, but we need to define the database itself first.


Make sure you’ve stopped debugging before you continue.

  1. Add a new SQL database to your project.

    In the Solution Explorer, right-click the Contacts project, select Add, and then choose New Item. Choose the SQL Database icon, and name it ContactDB.sdf.

    image with no caption
    image with no caption
  2. Click on the Add button in the Add New Item window.

    Watch it!

    If you’re not using the Express edition, you’ll see “Server Explorer” instead of “Database Explorer.”

    The Visual Studio 2010 Professional and Team Foundation editions don’t have a Database Explorer window. Instead, they have a Server Explorer window, which does everything the Database Explorer does, but also lets you explore data on your network.

  3. Cancel the Data Source Configuration Wizard.

    For now, we want to skip configuring a data source, so click the Cancel button. We’ll come back to this once we’ve set up our database structure.

  4. View your database in the Solution Explorer.

    Go to the Solution Explorer, and you’ll see that ContactDB has been added to the file list. Double-click ContactDB.sdf in the Solution Explorer and look at the left side of your screen. The Toolbox has changed to a Database Explorer.

The IDE created a database

image with no caption

When you told the IDE to add a new SQL database to your project, the IDE created a new database for you. A SQL database is a system that stores data for you in an organized, interrelated way. The IDE gives you all the tools you need to maintain your data and databases.

Data in a SQL database lives in tables. For now, you can think of a table like a spreadsheet. It organizes your information into columns and rows. The columns are the data categories, like a contact’s name and phone number, and each row is the data for one contact card.

image with no caption

SQL is its own language

SQL stands for Structured Query Language. It’s a programming language for accessing data in databases. It’s got its own syntax, keywords, and structure. SQL code takes the form of statements and queries, which access and retrieve the data. A SQL database can hold stored procedures, which are a bunch of SQL statements and queries that are stored in the database and can be run at any time. The IDE generates SQL statements and stored procedures for you automatically to let your program access the data in the database.


[note from marketing: Can we get a plug for Head First SQL in here?]

image with no caption

Creating the table for the Contact List

We have a database, and now we need to store information in it. But our information actually has to go into a table, the data structure that databases use to hold individual bits of data. For our application, let’s create a table called “People” to store all the contact information:

  1. Add a table to the ContactDB database.

    Right-click on Tables in the Database Explorer, and select Create Table. This will open up a window where you can define the columns in the table you just created.

    image with no caption

    Now we need to add columns to our table. First, let’s add a column called ContactID to our new People table, so that each Contact record has its own unique ID.

  2. Add a ContactID column to the People table.

    Type “ContactID” in the Column Name field, and select Int from the Data Type drop-down box. Be sure to select “No” for Allow Nulls.

    Finally, let’s make this the primary key of our table. Highlight the ContactID column you just created, and click the Primary Key button. This tells the database that each entry will have a unique primary key entry.

    image with no caption
    image with no caption
  3. Tell the database to autogenerate IDs.

    Since ContactID is a number for the database, and not our users, we can tell our database to handle creating and assigning IDs for us automatically. That way, we don’t have to worry about writing any code to do this.

    In the properties below your table, set Identity to “True” to make ContactID an identity column for your table.

    And make sure you specify the table name “People” in the Name box at the top of the window.

    image with no caption

The blanks on the contact card are columns in our People table

Now that you’ve created a primary key for the table, you need to define all of the fields you’re going to track in the database. Each field on our written contact card should become a column in the People table.

image with no caption

Brain Power

What kinds of problems could result from having multiple rows stored for the same person?

Finish building the table

image with no caption

Go back to where you entered the ContactID column and add the other five columns from the contact card. Here’s what your database table should look like when you’re done:

image with no caption

Click on the OK button to save your new table. This will add an empty table to your database.

image with no caption

Insert your card data into the database

Now you’re ready to start entering cards into the database. Here are some of the boss’s contacts—we’ll use those to set up the database with a few records.

  1. Expand Tables and then right-click on the People table in the Database Explorer (or Server Explorer) and select Show Table Data.

    image with no caption
  2. Once you see the Table grid in the main window, go ahead and add all of the data below. (You’ll see all null values at first—just type over them when you add your first row. And ignore the exclamation points that appear next to the data.) You don’t need to fill in the ContactID column; that happens automatically.


    Type “True” or “False” in the Client column. That’ll get translated to the way SQL stores yes or no info.

    image with no caption
    image with no caption
    image with no caption
  3. Once you’ve entered all six records, select Save All from the File menu again. That should save the records to the database.


    “Save All” tells the IDE to save everything in your application. That’s different from “Save”, which just saves the file you’re working on.

Connect your form to your database objects with a data source

We’re finally ready to build the .NET database objects that our form will use to talk to your database. We need a data source, which is really just a collection of SQL statements your program will use to talk to the ContactDB database.

  1. Go back to your application’s form.

    Close out the People table and the ContactDB database diagram. You should now have the Form1.cs [Design] tab visible.

    image with no caption
  2. Add a new data source to your application.

    This should be easy by now. Click the Data menu, and then select Add New Data Source...from the drop-down.

    image with no caption
    image with no caption
  3. Configure your new data source.

    Now you need to set up your data source to use the ContactDB database. Here’s what to do:

    • Step 1: Choose a Data Source Type. Select Database and click the Next button.

    • Step 2: Choose a Database Model. Select Dataset and click the Next button.

    • Step 3: Choose Your Data Connection. You should see your Contact database in the drop-down. Click Next.


      These steps connect your new data source with the People table in the ContactDB database.

    • Step 4: Choose Your Database Objects. Click the Tables checkbox.


      In the non-Express editions, you may be asked to save the connection in the app config. Answer “Yes.”

    • In the Dataset Name field, make sure it says “ContactDBDataSet” and click Finish.

    image with no caption

Add database-driven controls to your form

Now we can go back to our form and add some more controls. But these aren’t just any controls—they are controls that are bound to our database and the columns in the People table. That just means that a change to the data in one of the controls on the form automatically changes the data in the matching column in the database.


It took a little work, but now we’re back to creating form objects that interact with our data storage.

Here’s how to create several database-driven controls:

  1. Select the data source you want to use.

    Select Show Data Sources from the Data pull-down menu. This will bring up the Data Sources window, showing the sources you have set up for your application.

    image with no caption
  2. Select the People table.

    Under the ContactDBDataSet, you should see the People table and all of the columns in it. Click the “expand” icon next to the People table to expand it—you’ll see the columns that you added to your table. When you click on the People table in the Data Sources window and drag it onto your form, the IDE automatically adds data controls to your form that the user can use to browse and enter data. By default it adds a DataGridView, which lets the user work with the data using one big spreadsheet-like control. Click the arrow next to the People table and select Details—that tells the IDE to add individual controls to your form for each column in the table.

    image with no caption
    image with no caption
  3. Create controls that bind to the People table.

    Drag and drop the People table onto your form in the form designer window. You should see controls appear for each column in your database. Don’t worry too much about how they look right now; just make sure that they all appear on the form.

    image with no caption

Good programs are intuitive to use

Right now, the form works. But it doesn’t look that great. Your application has to do more than be functional. It should be easy to use. With just a few simple steps, you can make the form look a lot more like the paper cards we were using at the beginning of the chapter.

image with no caption
  1. Line up your fields and labels.

    Line up your fields and labels along the left edge of the form. Your form will look like other applications, and make your users feel more comfortable using it.

    image with no caption
  2. Change the Text Property on the Client checkbox.

    When you first drag the fields onto the form, your Client checkbox will have a label to the right that needs to be deleted. Right below the Solution Explorer, you’ll see the Properties window. Scroll down to the Text property and delete the “checkbox1” label.

    image with no caption
    image with no caption
  3. Make the application look professional.

    You can change the name of the form by clicking on any empty space within the form, and finding the Text property in the Properties window of your IDE. Change the name of the form to Objectville Paper Company Contact List.

    You can also turn off the Maximize and Minimize buttons in this same window, by looking for the MaximizeBox and MinimizeBox properties. Set these both to False.


    The reason you want to turn off the Maximize button is that maximizing your form won’t change the positions of the controls, so it’ll look weird.

    image with no caption

    A good application not only works, but is easy to use. It’s always a good idea to make sure it behaves as a typical user would expect it to.

Test drive

OK, just one more thing to do... run your program and make sure it works the way you think it should! Do it the same way you did before—press the F5 key on your keyboard, or click the green arrow button on the toolbar (or choose “Run” from the Debug menu).

You can always run your programs at any time, even when they’re not done—although if there’s an error in the code, the IDE will tell you and stop you from executing it.

image with no caption

Building your program overwrites the data in your database.

The IDE builds first, then runs


We’ll spend more time on this in the next chapter.

When you run your program in the IDE it actually does two things. First it builds your program, then it executes it. This involves a few distinct parts. It compiles the code, or turns it into an executable file. Then it places the compiled code, along with any resources and other files, into a subdirectory underneath the bin folder.

In this case, you’ll find the executable and SQL database file in bin/debug. Since it copies the database out each time, any changes you make will be lost the next time you run inside the IDE. But if you run the executable from Windows, it’ll save your data—until you build again, at which point the IDE will overwrite the SQL database with a new copy that contains the data you set up from inside the Database Explorer.

Watch it!

Every time you build your program, the IDE puts a fresh copy of the database in the bin folder. This will overwrite any data you added when you ran the program.

When you debug your program, the IDE rebuilds it if the code has changed—which means that your database will sometimes get overwritten when you run your program in the IDE. If you run the program directly from the bin/debug or bin/release folder, or if you use the installer to install it on your machine, then you won’t see this problem.

How to turn YOUR application into EVERYONE’S application

image with no caption

At this point, you’ve got a great program. But it only runs on your machine. That means that nobody else can use the app, pay you for it, see how great you are and hire you... and your boss and customers can’t see the reports you’re generating from the database.

C# makes it easy to take an application you’ve created, and deploy it. Deployment is taking an application and installing it onto other machines. And with the Visual C# IDE, you can set up a deployment with just two steps.

  1. Select Publish Contacts from the Project menu.

    image with no caption
  2. Just accept all of the defaults in the Publish Wizard by clicking Finish. You’ll see it package up your application and then show you a folder that has your Setup.exe in it.


    If you’re using Visual Studio Express, you’ll find “Publish” in the Project menu, but in other editions it may be in the Build menu.

image with no caption

Give your users the application

Once you’ve created a deployment, you’ll have a new folder called publish/. That folder has several things in it, all used for installation. The most important for your users is setup, a program that will let them install your program on their own computers.

image with no caption

Watch it!

You may need to run the installer as administrator.

If SQL Server Compact isn’t already installed on the machine, the installer will automatically download and install it. On some machines, this won’t work unless you run the setup as administrator, so right-click on “setup” and choose “Run as administrator” to install it. If you don’t have access to do that, don’t worry! You don’t need to in order to move forward in the book.

image with no caption

You’re NOT done: test your installation

image with no caption

Before you pop the cork on any champagne bottles, you need to test your deployment and installation. You wouldn’t give anyone your program without running it first, would you?

Close the Visual Studio IDE. Click the setup program, and select a location on your own computer to install the program. Now run it from there, and make sure it works like you expect. You can add and change records, too, and they’ll be saved to the database.

image with no caption

TEST EVERYTHING! Test your program, test your deployment, test the data in your application.

You’ve built a complete data-driven application

image with no caption

The Visual Studio IDE made it pretty easy to create a Windows application, create and design a database, and hook the two together. You even were able to build an installer with a few extra clicks.

image with no caption

The power of Visual C# is that you can quickly get up and running, and then focus on what your program’s supposed to do...not lots of windows, buttons, and SQL access code.

The best content for your career. Discover unlimited learning on demand for around $1/day.