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 for 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.

Note

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:

  • 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.

  • 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.

  • Create and interact with databases. The IDE includes a simple interface for building databases, and integrates seamlessly with SQL Server Express, as well as several other popular database systems.

  • 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 of 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.

    Note

    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 ski for the weekend, and expects a new address book program by the time he gets back. Otherwise... well... it 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.

  • ➊ 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
  • ➋ 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 that 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.

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 2008 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...

As soon as you save the project, the IDE creates a 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 2008\Projects\Contacts\.

Note

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.

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 still 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:

  • 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

    Relax

    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
  • 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:

    Note

    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
  • Download the Objectville Paper Company logo.

    Download the Objectville Paper Co. logo from Head First Labs (http://www.headfirstlabs.com/books/hfcsharp) 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 graphic 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
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 all of your files to My Documents\Visual Studio 2008\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.

image with no caption

Note

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

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.

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.

Note

Make sure you’ve stopped debugging before you continue.

  • 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.mdf.

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

  • 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.

  • 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.mdf in the Solution Explorer and look at the left side of your screen. The Toolbox has changed to a Database Explorer.

Watch it!

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

The Visual Studio 2008 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.

The IDE created a database

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.

image with no caption

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.

image with no caption

Note

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

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:

  • Add a table to the ContactDB database.

    Right click on Tables in the Database Explorer, and select Add New 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.

  • Add a ContactID column to the People table.

    Type “ContactID” in the Column Name field, and select Int from the Data Type dropdown box. Be sure to uncheck the Allow Nulls checkbox.

    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
  • Tell the database to auto-generate 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, scroll down to Identity Specification, click the + button, and select Yes next to the (Is Identity) property.

    image with no caption

The blanks on 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 Save button on the toolbar to save your new table. You’ll be asked for a name. Call it “People” and click OK.

image with no caption

Diagram your data

The Visual Studio IDE is built to work with databases, and it comes with a lot of built-in tools that help you when you’re handling a lot of data. One of the most powerful tools you have is the database diagram, which you can use to view and edit complex relationships between the tables in your database. So let’s go ahead and build a database diagram for your database.

Relax

In very rare cases, a few people sometimes have problems getting the SQL database to work.

If you run into any trouble, don’t worry—go to the Head First C# forum at http://www.headfirstlabs.com/ for help troubleshooting the problem.

  • Create a new database diagram.

    Go to the Database Explorer window and right-click on the Database Diagrams node. Select Add New Diagram.

    image with no caption
  • Let the IDE generate access code.

    Before you tell the IDE about your specific table, it needs to create some basic stored procedures for interacting with your database. Just click Yes here, and let the IDE go to work.

    image with no caption
  • Select the tables you want to work with.

    Select the People table from the window that pops up, and click Add. Now the IDE is ready to generate code specific to your table.

    image with no caption
    image with no caption
  • Name your diagram PeopleDiagram.

    Select File>Save Diagram. You’ll be asked to name your new database diagram. Call it PeopleDiagram, and you’re all set.

    Note

    If you’re using Visual Studio 2005, select File>Save All instead.

    image with no caption

A database diagram describes your tables to the Visual Studio IDE. The IDE will read your database and build a database diagram for you automatically.

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.

  • ➊ 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
  • ➋ 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.

    Note

    Type “True” or “False” in the Client column. That’s how SQL stores yes or no info.

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

    Note

    “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.

  • 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
  • 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
  • Configure your new data source.

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

    • Select Database and click the Next button.

    • Click Next in the “Choose your Data Connection” screen.

    • Make sure the Save the connection checkbox is checked in the “Save the Connection” screen that follows and click Next.

      Note

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

    • In the “Choose Your Objects” screen, click the Table checkbox.

    • 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.

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

Note

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

  • 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 setup for your application.

    image with no caption
  • Select the People table.

    Under the ContactDBDataSet, you should see the People table and all of the columns in it. Click the plus sign 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
  • Create controls that bind to the People table.

    Drag and drop the People table onto your form. 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
  • 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
  • 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
  • Make the application look professional.

    You can change the name of the form by clicking on any 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 Co. - 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.

    Note

    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

Okay, 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.

Note

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.

  • ➊ Select Publish Contacts from the Build menu.

    image with no caption
  • ➋ 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.

    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

You built a complete data-driven application

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 built a complete data-driven application

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
image with no caption

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

CSharpcross

Take some time to sit back and exercise your C# vocabulary with this crossword; all of the solution words are from this chapter.

image with no caption

Across

Down

1. When you do this from inside the IDE, it’s called “debugging”.

3. The ______ explorer is where you edit the contents of your SQL tables and bind them to your program.

5. The “About” box in the Contact List program was one of these.

6. You build one of these so you can deploy your program to another computer.

9. An image, sound, icon or file that’s attached to your project in a way that your objects can access easily.

11. Before you can run your program, the IDE does this to create the executable and move files to the output directory.

14. The database ____________ gives the IDE information about your database so it can generate SQL statements automatically.

16. The ___________ explorer in the IDE is where you’ll find the files in your project.

17. Drag one of these objects onto your form to display an image.

18. A stored ___________ is a way for a SQL database to save queries and statements that you can reuse later.

2. What’s happening when code is turned into an executable.

4. A SQL database can use many of these to store its data.

7. What you change to alter the appearance or behavior of objects on your form.

8. What you’re doing to your program when you run it from inside the IDE.

10. Every row in a database contains several of these, and all of them can have different data types.

12. Before you start building any application, always think about the users and their ________.

13. You drag objects out of this and onto your form.

15. When you double-clicked on a visual control, the IDE created this for you and you added code to it.

CSharpcross Solution

image with no caption

Get Head First C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.