Sunteți pe pagina 1din 13

Introduction to Visual C# 2008 Express Edition

Contents
..............................................................................................................................................1 Introduction to Visual C# 2008 Express Edition.................................................................1 Contents...............................................................................................................................1 Part 1: Setup.................................................................................................................1 Part 2: Creating a Project.............................................................................................3 Part 3: The Windows Form Designer..........................................................................3 Part 4: Writing C# code...............................................................................................6 Part 5: Compiling, Running and Saving your project .................................................7 Part 6: Errors and Debugging......................................................................................9 Part 7: Project Files, Properties and Customization...................................................10 Part 8: Data................................................................................................................11 Part 9: Where to go from here....................................................................................13
Hello. My name is Jacqueline Russell and I am a Product Manager at Microsoft for the Visual Studio Express Editions which are a set of free, easy-to-use tools for hobbyists and amateurs to create unique projects and all sorts of different software applications. Ive been creating windows and web applications for my own amusement and for friends and family for quite a while now. If this is your first software project, then youre in for a treat, and dont worry if I can do this stuff, then you can too! In this introductory video, Ill go over some of the main features of Visual C# 2008 Express, and cover some of the most common tasks youll be doing as you create your programs. By the end of this video, youll be more familiar with the development environment and able to get started creating your first application. I encourage you to follow along with me as I go through this video, and if I go over any steps too fast, go ahead and use that pause button. If you are already an experienced Visual Studio user, then you may not learn anything new from these introductory videos. But regardless of your skill level, Visual C# 2008 Express is a powerful tool that can help turn your idea-ware into software!

Part 1: Setup
============= First, let's get started by downloading and installing the software, which you can do from the Visual Studio Express Home page on http://www.microsoft.com/express/.

You should check whether your computer meets the requirements before installing. You can find this under the Support section of the website. Click on the "Download" button to get to the Downloads page and then click on Visual C# Express to begin the download process. If you have installed a beta version of Visual Studio 2008 Express, then it is important to uninstall this before continuing. If you would like to create an installation CD or if you need to perform an installation disconnected from the internet, then you can download an IMG file that contains the complete setup in the Offline Download section. ~~~ Run Setup ~~~ When you start the install process, this first screen asks if you want to give feedback to Microsoft on your setup experience. <Next> Then you will be asked to accept the license agreement. <Next> The next screen presents an additional installation option. Note that if youve already installed another Express product and selected this option, then this screen may not appear. The MSDN Express Library is a useful additional download that installs product documentation and help files locally onto your computer, so you can access support information while disconnected from the internet. <Next> This screen shows us whats about to be installed (this list may vary based on existing installed components): .NET Framework 3.5 C# Express MSDN Library SQL CE SQL CE Design Tools SQL Server Compact Edition is great complementary, free product that is the default database automatically installed with Visual C# Express and is good to have if you plan on creating any data-driven applications such as a collection tracking program or a reporting utility. Notice that this is a change from Visual C# 2005 which uses SQL Server Express Edition as the default database engine. In comparison, SQL Server Compact Edition is a lighter weight version and a bit easier to use. However, if you do want to use the SQL Server Express Edition, it is also provided as a free download on the Express website, and also works well with Visual C # 2008 Express Edition. <Next> Please be patient during the installation process on some older computers the installation may take up to an hour. You may also be prompted to reboot your computer so make sure you have saved any open documents. On this last screen you can check for any updates. When you get a chance I would highly recommend that you register the product. This quick step gives you access to some free resources such as e-books to help you get started working with Visual C# Express, some free images from Corbis to use on your applications, and lots of other cool components and discounts. It also allows you to enjoy uninterrupted use of the Visual C# development environment because otherwise, the software will expire after 30 days.

Part 2: Creating a Project


================================== Now that the installation is complete, you can run the C# Express from the Start menu, under "All Programs". The first time you run it, it may take a few moments to load. ~~~ Run Visual C# 2008 Express ~~~ The first thing youre presented with is something called the Start Page. This has some useful links: You can open projects you've worked on recently See samples and tutorials in the Getting Started section And view the latest news headlines for recreational developers Let's dive right in and create a new project. From the File menu, select New Project. ~~~ File | New Project ~~~ This window that appears offers several different project templates that can be used as starting points for your project, depending on what type of application you want to create.

The "Windows Forms Application" template lets you easily design familiar windows-style applications. The "Class Library" template allows you to create a block of code that can be reused by several different applications. The "Console Application" template creates a program that uses a simple text interface which runs in the command window (DOS prompt). You can also create an Empty Project that wont automatically setup anything for you Something thats new in Visual C# 2008 is the WPF Application and WPF Browser Application templates. WPF stands for Windows Presentation Foundation and is a new technology that allows you to create applications with a rich graphical user interface. A great example of a WPF application is this snowboarding app which uses all sorts of rich media interfaces to present a real users day of riding on the mountain. ~~~ Demo http://www.metaliq.com/wpf ~~~

Unfortunately we dont have time to cover WPF in this video, but if you want to learn more, there are plenty of tutorials and resources on the web to help you.

Part 3: The Windows Form Designer


============================================ Let's go ahead and build a Windows Forms application. We can name the new project anything that we'd like. This becomes the name of the folder in which the application is built, and also the name of the executable file thats created for our program. We will call this project "Desktop Window".

Visual C# gives us a head-start on our project by providing us with a blank window or form that is already started for us. A form is a container upon which you can place controls to define the interface of your application. There are some familiar windows components already here at the top of our form: An icon that you can customize in the top left corner A title for the form. The first form is called Form1 by default. And the minimize, maximize & close buttons in the upper right hand corner Notice that when we click on our form, these white squares appear at the edges of our form. This allows us to resize the form. You can see that our Form opened in a separate tab called Form1.vb [Design] overlaying the Start Page that we were looking at before. This is called the Designer view of our program. On the right side of the Designer is a window called the Solution Explorer. In the same way that you can manage and navigate files on your computer system with the Windows Explorer, you can use the Solution Explorer to manage and navigate the files in your solution. Right now our Desktop Window project contains 2 folders: Properties contains the properties for our project References contains all the libraries that our project references And 2 files: Form1.cs our Form Program.cs the main code for our program Besides the Solution Explorer window, another window you will use a lot is the Properties window. Select View | Properties Window to display this below the Solution Explorer window. ~~~ View | Properties Window ~~~ This window shows all the properties or settings associated with the selected object. For example, if we click on Form1, the Properties window updates to be focused on that object. Its easy to use the Properties window to modify the settings of an object we can just change the value in the right column next to the name of the property. For example, we can change the appearance of this form by setting its properties. Lets go ahead and change the title on our form from Form1 to My Window. Text = My Window And lets set another property that well use later called Transparency Key. By picking a certain color from this palette (lets use a Lime green color), we are assigning it to be transparent. Youll see a bit later on how this will work. TransparencyKey = Lime On the left side of the Designer youll see a tab that says Toolbox. When you hover the mouse over it, the window will pop out and then pop back in when you move the mouse away. Lets go ahead and pin this window in place using this pushpin icon on the top right corner. The Toolbox contains a list of all types of different controls you can use in your project. You can think of controls as common building blocks that provide interactive functionality on a form, such as checkboxes, calendars, and grids of data. Some controls are containers for other controls, such as our blank Form1.

To place controls on your form, simply drag and drop them from the Toolbox onto the Form in the Designer. ~~~ Drag textbox, button, label, radiobutton onto form & move them around ~~~ These snap lines help you to place controls with a consistent spacing and alignment, giving a pleasing look to the layout of your form. Notice that the controls are grouped into categories depending on what theyre used for. You can expand or collapse these groups by clicking on the plus or minus signs. ~~~ Expand/Collapse groups & Scroll slowly (keep mouse off controls) ~~~ For example, there are different categories for controls dealing with Menus & Toolbars, Data, and Printing. If you hover your mouse over a control, you will be able to get a description of what that control does. ~~~ Hover mouse over RichTextBox ~~~ To remove controls from your form, you can right-click on them and select Delete, or you can select multiple controls at once and press the Delete key on your keyboard. ~~~ Delete all controls except Label & Button on form ~~~ Now lets look at the Dialog controls. ~~~ Expand Dialogs in Toolbox ~~~ The nice thing about these is that instead of having to build out commonly-used forms, these dialog boxes allow you to use common screens that are built into the Windows operating system itself. Among these dialogs are the very common forms to open or save a file, ~~~ Hover mouse over OpenFileDialog & SaveFileDialog ~~~ and also this one that lets the user choose a color, the ColorDialog. Lets add this to our form. ~~~ Drag ColorDialog onto Form ~~~ Because these dialog controls only become visible when required, the designer shows them at the bottom of the screen, off the form. But we can treat them the same as any other control, theyre just not visible on the Form. The controls weve placed get named according to the type of control, with a number afterwards like Button1 or ColorDialog1. We see these names in the Properties window when we click on the control. And we can also see a list of all the controls in our project including our Form using this drop-down box at the top of the Properties window. ~~~ Highlight Name field in Properties Window | Click on Dropdown box ~~~ There is a great variety of property settings available to us in the Property window, such as color, size, font, and so on. And notice the descriptive text that appears at

the bottom of the Properties window as we select various properties. Lets change some of the properties for our Label control. ~~~ Click on Label ~~~ Text = Desktop Window ForeColor = Red Font Size = 14 Font Bold = True Each control has a different assortment of properties depending on what it does. Using the toolbar at the top of the window you can sort this list alphabetically, or by groups of property types. ~~~ Click Toolbar sort buttons ~~~ Now lets tie our Button and our ColorDialog controls together so when the button is clicked, it brings up the color picker dialog? To give the user a better idea of what the button will do, we can modify the text that appears on the button. ~~~ Click on the Button control, modify the Text property = Pick a Color ~~~

Part 4: Writing C# code


===================== Each Windows form is defined both by its design, which we have seen so far, and also by its underlying code. To see the code for your form, just select View | Code from the menu bar or alternately, right click on the Form in the Solution Explorer and select View Code. ~~~ Right-click on Form | Select View Code ~~~ Notice that the Code editor window opens up in a new tab. We can also drag one of the tabs down to create a new tab group, and see both views at once. ~~~ Create a horizontal tab group ~~~ This is especially nice if you have a big monitor, and want to work on two sections of the application at once. ~~~ Drag back to original tab group ~~~ Right now the code for our Form1 is empty because our Form doesnt do anything, but lets add some code to make the Button show the Color Dialog when its clicked. ~~~ Select Form Designer View ~~~ When a user acts on a control, for instance by clicking a button, it initiates an action on the control called an Event. You can see the list of Events associated with a particular control by selecting the control and clicking on the lightning bolt button in the Properties Pane. ~~~ Select Button | Click lightening button in Properties Window ~~~

With so many different types of Button Events listed here, its nice that the most common, or default, event for a control can easily be configured by just doubleclicking on the control. ~~~ Double-click on button ~~~ This brings us to the Code Editor view for the Button Click event. In the case of the button, we see that the default event is the Click event, and we also see that Visual C# Express has automatically built out an area of code that will run when the button is clicked. This is empty at the moment, but lets add a line of code that will display our Color Picker dialog control. We wont go into much detail about the C# programming language in this video, but you can learn more at the Beginner Developer Learning Center (http://msdn.com/beginner). colorDialog1. Notice that as you type, little popup windows appear listing the names of controls and their associated properties and options. This feature of Visual Basic Express is called "IntelliSense", and is a way to provide context-sensitive help and guidance while you code. Meaning, that depending on what you're writing at the time, just the right options that are valid are shown. This feature is very useful to discover the functionality found in objects and helps you find property names for a given control if you dont happen to remember them off the top of your head. ShowDialog(); Now, lets set the background color of the form equal to the selected color of our Color Dialog control: this.BackColor = colorDialog1.Color; Note that this is a special keyword in C# used to refer to the Form itself. Putting comments in your code is a great idea to let other people know what you had intended with a block of code. These comments are ignored by the computer when it runs your program and can be placed anywhere. To use comments in C#, just precede the line with two slashes, and notice that comments are marked in green in the Code Editor. //Display Color Dialog //Set the forms background color Theres also a very handy feature on the toolbar to allow you to quickly comment and uncomment the selected lines in the Code Editor. ~~~ Click on Comment and Uncomment toolbar buttons ~~~

Part 5: Compiling, Running and Saving your project


====================== Compiling or Building your project is the process of converting all the code youve written into an executable file that can be run. This also has the effect of doing some checking to your code for mistakes. Lets build our project and see if there are any

errors. Select Build Solution from the Build menu, and we can then see the results at the bottom left of the screen. ~~~ Build | Build Desktop Window ~~~ So far so good. Now for the fun part! Let's see how our application performs by running it. We can use the green "Play" button, or we can also select "Start Debugging" from the "Debug" menu. If you hadnt yet compiled your code before doing this, it will automatically compile everything before running, so you can skip the Build stage if you are confident you dont have any bugs. ~~~ Debug | Start Debugging ~~~ Ta-da! Heres our running program! Notice that while our program is running, you wont be able to edit it in Visual C# Express. ~~~ Click on IDE | type in code editor | Mouse at bottom error msg ~~~ Now for the moment of truth, what happens when we click the Change Color button? Sure enough, it brings up the ColorDialog, and were able to change the color of our form. What happens when we pick White as the color? Look at that, our form becomes transparent! This is because, if you remember, we set the Forms transparency key property to White. To close our program, we can just click the Red X on the top right corner of our form. ~~~ Close Form ~~~ Now lets save our project by selecting Save All from the File menu. ~~~ File | Save All ~~~ By default, projects are stored in their own folder under My Documents | Visual Studio 2008 | Projects. Lets look at this directory in Windows Explorer. ~~~ Open Windows Explorer ~~~ We see a couple files and a folder in this directory. The Desktop Window "Solution File" has a .SLN extension and contains all references to your project. This is the file that you will double-click to open up your project again in Visual C# Express. You can ignore the file with the .SUO extension for now, it just contains some user options that you set for your solution. Lets look in the Desktop Window project folder. This contains all the files related to your project. The bin folder is where Visual Studio puts together the actual executable file for us. "bin" is short for "Binary". When we compiled or built our project Visual Studio created this folder. Notice that there are 2 versions the Release (or final) version, and the Debug version of our program. To run our program we just double-click the Desktop Window.exe file in one of these folders. ~~~ Double-click executable file ~~~

You can share the programs you create with others by simply copying the files that are generated in this folder to another computer that also has the .NET Framework installed. ~~~ Navigate back up to Project folder ~~~ The obj folder contains some intermediate project files that you can ignore for now. The Properties folder contains files that pertain to your projects properties and settings. The Desktop Window .csproj and .csproj.user files are your project files, and weve seen the Form1 files and the Program.cs file previously in the Solution Explorer.

Part 6: Errors and Debugging


================================ As you write code, there will be occasions that you make small mistakes. In the world of software development, these are called bugs. Fortunately, Visual C# Express can automatically find some kinds of errors for you. These bugs will appear underlined in either blue or red squiggly lines in the Code Editor, similar to misspellings in the Microsoft Word program. Lets look at this in our code. Say we accidentally use the wrong property name, for example MyColor instead of Color. this.BackColor = colorDialog1.MyColor Now if we try to compile or build our project, ~~~ Build | Build Solution ~~~ notice that Visual C# Express gives us an error and underlines this as a mistake. We can see the specific error message by moving our mouse over the underlined section. Sometimes a program will compile and run, but not produce the results you expected. Debug mode is also useful in this case to diagnose these logic errors. You can manually set a place in the code where the execution will halt, called a breakpoint. This is done by clicking to the left of the line of code of interest. ~~~ Insert Breakpoint at colorDialog1.ShowDialog() ~~~ Then when you run the application in Debug mode, it halts on that line so you can examine all the variables, and find the area of your code that is not working as expected. The program is still in memory, and just frozen at this point. ~~~ Click Play ~~~ In this break mode you can step line-by-line through the application by using either the Step Into or Step Over feature. Step Into offers a more thorough analysis of the code because it digs into any methods that are called from here, whereas Step Over will skip these called methods. ~~~ Debug | Step Over ~~~

A great way to examine the contents of variables is by using Visualizers. This handy feature lets you drill down into various properties and values held in a variable or object. If we hover our mouse over the highlighted area of code, we can see all the information held inside a Color object. There are several other useful debugging windows: Locals window shows all the variables local to the currently executing method Watch window you can add any variable to the Watch window to monitor its value ~~~ Right-click ColorDialog1 | Add Watch ~~~ Immediate window this is like a scratch pad where you can perform quick calculations, print out values and execute commands ~~~ Type ? 1+2 ~~~ To stop the debugging so that we can edit again, we can select Stop Debugging from the Debug menu. ~~~ Select Debug | Stop Debugging ~~~ ~~~ Remove Breakpoint ~~~

Part 7: Project Files, Properties and Customization


============================ To add more files to your project, from the Project menu, you can select Add New Item, or you can right-click your Desktop Window project in the Solution Explorer and select Add New Item. ~~~ Right-click Desktop Window | Select Add | New Item ~~~ This will bring up the Add New Item dialog box. There are a bunch of different templates here you can choose from with descriptions at the bottom explaining each one. Lets add another Windows Form. ~~~ Select Windows Form | Click Add ~~~ We see that Form2 has been added to our project. We can connect Form1 and Form2 together. First, lets add another button to Form1 and set the button Text to tell the user what will happen when they click the button. ~~~ Drag button onto Form1 | Text = Show Form2 ~~~ Now we need to actually hook them up in code. Double-click the button to go to the code view and insert: Form2 myForm2 = new Form2(); myForm2.Show(); Now if we run our program, and click on the Show Form2 button, our second form gets displayed. ~~~ Click Play | Click Show Form2 | Close Windows ~~~

Alright. Now lets take a look at the properties of our Desktop Window project. We can do this by double-clicking on the Properties folder in the Solution Explorer. ~~~ Double-click My Project ~~~ We can see that the properties of our project are divided into categories which are listed on these tabs to the left. Some of the things you can do here are to define custom user or application settings, or set up your application to be published on the Internet. Lets set up a custom icon for our application. We can do this in the Application section. Icons are simple 16 by 16 or 32 by 32 bitmaps with a .ico file extension, and some sample icons are available to you for free as part of your Express registration benefits. Lets browse to a sample icon. ~~~ Icon Drop-down Browse | Select MSN.ico | Open | Build Solution ~~~ Now when we look at our executable file, we see that it uses the new icon. ~~~ Open Windows explorer to bin\Release ~~~ You can customize your development environment by setting configuration options found in the Tools | Options window. ~~~ Tools | Options ~~~ Here you can specify things like window layout, font styles, keyboard shortcuts and more. For example, I can add line numbers to my Code Editor view here under Text Editor Basic | Editor by checking the Line Numbers box. ~~~ Text Editor | Basic | Editor | Line numbers ~~~ And you can also set things like fonts and colors. ~~~ Environment | Fonts and Colors | Set Item foreground/background colors ~~~ To see all the configuration options available to you, click the Show all settings checkbox.

Part 8: Data
========================== Many applications become very useful when they can store information. And one of the best ways to store information is in a database. This way the data can be organized just the way you need. In this demonstration, we will create a connection to an existing sample database from Microsoft called Northwind using SQL Server Compact Edition. Well start by getting a connection to a database. From the Data menu, select Show Data Sources. The Data Sources window will be displayed. We can move windows around simply by dragging and dropping lets move this Data Sources window from the Toolbox area over to the Solution Explorer area where it becomes a tabbed overlay on the Solution Explorer window. We see that there are no data sources yet established, so we can select Add New Data Source. This brings up the

Data Source Configuration Wizard. We see that we can connect to several data sources, including a Web Service or an Object. In this case well connect to a database file on this local computer. ~~~ Data Sources | Add New Data Source | Database | Next ~~~ Once we pick the database source, we need to configure a data connection, so well click New Connection. We can see that the default database type is SQL Server Compact Edition. But you could pick another database type such as Access or SQL Server Express. ~~~ New Connection | Change | Cancel ~~~ Now lets Browse for our Northwind database file. You can select Test Connection to make sure that we set this up properly. ~~~ Browse... | Northwind.sdf | Open | Test Connection|OK ~~~ You are prompted to copy this data file into your project and give it a name so that you can deploy the database with your project to other machines, and it can be packaged up along with the rest of your project files. Now we can see all the tables in this Nothwind database. Lets select the Employees Table, and change the DataSet name to something more descriptive, like EmployeesDataSet. ~~~ DataSet name = EmployeesDataSet | Finish ~~~ We can see our new Data connection shown in the Data Sources window. Lets configure our Form2 to show this data in our Employees table. Select Form2, and simply drag and drop the entire Employees table from the Data Sources window onto the Form. ~~~ Drag table onto Form2 | resize DataGrid ~~~ This creates a DataGridView control, as well as this neat little strip of buttons at the top called a BindingNavigator. There is also code written automatically for us to give these controls life. Theres nothing else we have to do in order to work with our data its almost too easy! Lets run the application to see how it functions. ~~~ Click Play ~~~ When we click the Show Form2 button, we can see all the data in our Employees table, and navigate through the list using the toolbar buttons. Notice that these buttons will also allow you to add new employees and delete employees. Another way to access data is through a technology called LINQ. LINQ stands for Language Integrated Query which allows you model data constructs and work with data directly in your code. For example, you could write something like this to pull out Employee last names: var q = from e in db.Employees

select e.LastName; If youre new to data storage concepts, that may not mean much, but basically it gives you easier accessibility to your data, and more flexibility in working with your data directly in your program. Unfortunately we dont have time to cover LINQ in more detail here, but if youre planning on creating an application that makes use of databases or XML data files, I encourage you to explore this method of data access. There are many resources and tutorials on the web that will help you understand and use LINQ in your windows applications.

Part 9: Where to go from here


======================== So now that weve covered some of the main features of Visual C# 2008 Express, inevitably when youre creating your own projects, youll have some questions about how to achieve certain functionality. Visual Studio offers excellent help features to answer those questions. From the Help menu you can Search for certain topics or use the How do I help feature to find out about specific tasks. Also when youre programming if you want to learn about a specific method, property or keyword, you can just select the term in the Code Editor and press the F1 key to bring up the related Help article. ~~~ Select this | Press F1 ~~~ A great place to learn more about programming is the Beginner Developer Learning Center at http://msdn.com/beginner. ~~~ IE Navigate to msdn.com/beginner ~~~ Here youll find all sorts of free tutorials and lessons to increase your programming knowledge. You can pick from Windows or Web development learning tracks and choose lessons from Tier 1 3 difficulty levels. Theres also a How-To reference library if you just want a quick refresher on a certain topic, and the Kids Corner contains lessons specifically for kids. If you run into a problem and need to ask a question, you can do that in the Express forums. You can find links to the forums and other resources on the Start Page. ~~~ Click MSDN Forums link on Start Page ~~~ We hope youve had fun with this quick introduction about how to start using the Microsoft Visual C# 2008 Express Edition. Youre now ready to fire up the code editor, and start cranking out some cool Windows applications!

S-ar putea să vă placă și