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.
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.
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.
➊ 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.
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.
➊ 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.
➋ 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.
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:
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\.
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.
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.
➊ 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.
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.
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.
➌ 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.
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.
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:
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: .
When you run your program, Visual Studio copies all of your files to
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.
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.
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.
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.
➊ 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.
➋ 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
➋ 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.
➌ 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.
Select File>Save Diagram. You’ll be asked to name your new database diagram. Call it PeopleDiagram, and you’re all set.
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.
➊ Expand Tables and then right click on the People Table in the Database Explorer (or Server Explorer) and select Show Table Data.
➋ 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.
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.
➋ 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.
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.
In the “Choose Your Objects” screen, click the Table checkbox.
In the Dataset Name field, make sure it says “ContactDBDataSet” and click Finish.
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:
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.
➋ 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.
➌ 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.
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.
➊ 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.
➋ 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.
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.
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.
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.
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.
Building your program overwrites the data in your database.
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.
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/release folder, or if you use the installer to install it on your machine, then you won’t see this problem.
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.
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.
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.
TEST EVERYTHING! Test your program, test your deployment, test the data in your 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.
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.
Take some time to sit back and exercise your C# vocabulary with this crossword; all of the solution words are from this chapter.
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.