Coding Skills for a Windows Form Application

If you want to learn how to code and test a Windows form application, look no further. This article, the second of three parts, helps you brush up your coding skills. It is excerpted from chapter three of the book Murach's C# 2005, written by Joel Murach (Murach, 2005; ISBN: 9781890774370).

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 16
June 29, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

How to detect and correct syntax errors
 
As you enter code, Visual Studio checks the syntax of each statement. If a syntax error, or build error, is detected, Visual Studio displays a wavy line under the code in the Code Editor. In the Code Editor in figure 3-6, for example, you can see the lines under txtPercent and txtAmount.

If you place the mouse pointer over the code in error, a brief description of the error is displayed. In this case, the error message indicates that the name does not exist. That’s because the names entered in the Code Editor don’t match the names used by the Form Designer. If the names are correct in the Form Designer, you can easily correct these errors, by editing the names in the Code Editor. In this figure, for example, the names of the text boxes should be txtDiscountPercent and txtDiscountAmount.

If the Error List window is open as shown in this figure, any errors that Visual Studio detects will also be displayed in that window. If the Error List window isn’t open, you can display it by pointing to the Error List tab that’s displayed on the lower edge of Visual Studio. Then, you can jump to the error in the Code Editor by double-clicking on it in the Error List window.

When you’re first getting started with C#, you will inevitably encounter a lot of errors. As a result, you may want to use the Auto Hide button that’s available from the Error List window to keep it open all the time. This makes it easy to see errors as soon as they occur. Then, once you get the hang of working with C#, you can conserve screen space by using the Auto Hide button so this window is only displayed when you point to the Error List tab.

By the way, Visual Studio isn’t able to detect all syntax errors as you enter code. Instead, some syntax errors aren’t detected until the project is built. You’ll learn more about building projects later in this chapter.

The Code Editor and Error List windows with syntax errors displayed


Figure 3-6.  How to detect and correct systax errors

Description

  • Visual Studio checks the syntax of your C# code as you enter it. If a syntax error (or build error) is detected, it’s highlighted with a wavy underline in the Code Editor, and you can place the mouse pointer over it to display a description of the error.
  • If the Error List window is open, all of the build errors are listed in that window. Then, you can double-click on any error in the list to take you to its location in the Code Editor. When you correct the error, it’s removed from the error list.
  • If the Error List window isn’t open, you can display it by selecting the Error List command from the View menu. Then, you can click the Error List tab that’s displayed at the edge of the Visual Studio window. If you prefer, you can click its Auto Hide button to keep it displayed.
  • Visual Studio doesn’t detect some syntax errors until the project is built. As a result, you may encounter more syntax errors when you build and run the project.

More coding skills
 
At this point, you should understand the mechanics of adding code to a form. To code effectively, however, you’ll need some additional skills. The topics that follow present some of the most useful coding skills.

How to code with a readable style


 
In figure 3-5, you learned some coding rules that you must follow when you enter the code for an application. If you don’t, Visual Studio reports syntax errors that you have to correct before you can continue. You saw how that worked in the last figure.

Besides adhering to the coding rules, though, you should try to write your code so it’s easy to read, debug, and maintain. That’s important for you, but it’s even more important if someone else has to take over the maintenance of your code. You can create more readable code by following the three coding recommendations presented in figure 3-7.

To illustrate, this figure presents two versions of an event handler. Both versions accomplish the same task. As you can see, however, the first one is easier to read than the second one because it follows our coding recommendations.

The first coding recommendation is to use indentation and extra spaces to align related elements in your code. This is possible because you can use one or more spaces, tabs, or returns to separate the elements in a C# statement. In this example, all of the statements within the event handler are indented. In addition, the if-else statements are indented and aligned so you can easily identify the parts of this statement.

The second recommendation is to separate the words, values, and operators in each statement with spaces. In the unreadable code in this figure, for example, you can see that each line of code except for the method declaration includes at least one operator. Because the operators aren’t separated from the word or value on each side of the operator, the code is difficult to read. In contrast, the readable code includes a space on both sides of each operator.

The third recommendation is to use blank lines before and after groups of related statements to set them off from the rest of the code. This too is illustrated by the first method in this figure. Here, the code is separated into five groups of statements. In a short method like this one, this isn’t too important, but it can make a long method much easier to follow.

Throughout this chapter and book, you’ll see code that illustrates the use of these recommendations. You will also receive other coding recommendations that will help you write code that is easy to read, debug, and maintain.

As you enter code, the Code Editor will automatically assist you in formatting your code. When you press the Enter key at the end of a statement, for example, the Editor will indent the next statement to the same level.

A method written in a readable style

  private void btnCalculate_Click(object sender, System.EventArgs e)
  {
     decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

     decimal discountPercent = 0m;
     if (subtotal >= 500)
     { 
        
discountPercent = .2m;
     }
     else if (subtotal >= 250 && subtotal < 500)
     {
       
discountPercent = .15m;
     }
     else if (subtotal >= 100 && subtotal < 250)
     {
       
discountPercent = .1m;
     } 

     decimal discountAmount = subtotal * discountPercent;
     decimal invoiceTotal = subtotal - discountAmount;

     txtDiscountPercent.Text = discountPercent.ToString("p1");
     txtDiscountAmount.Text = discountAmount.ToString("c");
     txtTotal.Text = invoiceTotal.ToString("c");

     txtSubtotal.Focus();
  }

A method written in an unreadable style

  private void btnCalculate_Click(object sender, System.EventArgs e){
  decimal subtotal=Convert.ToDecimal(txtSubtotal.Text);
  decimal discountPercent=0m;
  if (subtotal>=500) discountPercent=.2m;
  else if (subtotal>=250&&subtotal<500) discountPercent=.15m;
  else if (subtotal>=100&&subtotal<250) discountPercent=.1m;
  decimal discountAmount=subtotal*discountPercent;
  decimal invoiceTotal=subtotal-discountAmount; 
  txtDiscountPercent.Text= discountPercent.ToString("p1"); 
  txtDiscountAmount.Text= discountAmount.ToString("c");
  txtTotal.Text=invoiceTotal.ToString("c");
  txtSubtotal.Focus();
  }

Coding recommendations

  • Use indentation and extra spaces to align statements and blocks of code so they reflect the structure of the program.
  • Use spaces to separate the words, operators, and values in each statement.
  • Use blank lines before and after groups of related statements.

Note

  • As you enter code in the Code Editor, Visual Studio may adjust its indentation.

Figure 3-7    How to code with a readable style

How to code comments


 
Comments are used to document what the program does and what specific blocks and lines of code do. Since the C# compiler ignores comments, you can include them anywhere in a program without affecting your code. Figure 3-8 shows you how to code two types of comments.

First, this figure shows a delimited comment at the start of a method. This type of comment is typically used to document information that applies to an entire method or to any other large block of code. You can include any useful or helpful information in a delimited comment such as a general description of the block, the author’s name, the completion date, the files used by the block, and so on.

To document the purpose of a single line of code, you can use single-line comments. Once the compiler reads the slashes (//) that start this type of comment, it ignores all characters until the end of the current line. In this figure, single-line comments have been used to describe each group of statements. In addition, single-line comments have been used at the end of some lines of code to clarify the code.

Although many programmers sprinkle their code with comments, that shouldn’t be necessary if you write your code so it’s easy to read and understand. Instead, you should use comments only to clarify code that’s difficult to understand. The trick, of course, is to provide comments for the code that needs explanation without cluttering the code with unnecessary comments. For example, an experienced C# programmer wouldn’t need any of the comments shown in this figure.

One problem with comments is that they may not accurately represent what the code does. This often happens when a programmer changes the code, but doesn’t change the comments that go along with it. Then it’s even harder to understand the code, because the comments are misleading. So if you change the code that has comments, be sure to change the comments too.

Incidentally, all comments are displayed in the Code Editor in a different color from the words in the C# statements. By default, the C# code is blue and black (blue for C# keywords and black for the rest of the code), while the comments are green. That makes it easy to identify the comments.

A method with comments

  private void btnCalculate_Click(object sender, System.EventArgs e)
{
     /**********************************
     * this method calculates the total
     * for an invoice depending on a
    
* discount that’s based on the subtotal   
     **********************************/

     // get the subtotal amount from the Subtotal text box
     decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);

     // set the discountPercent variable based
     // on the value of the subtotal variable
     decimal discountPercent = 0m; // the m indicates a decimal value
     if (subtotal >= 500)
     {
       
discountPercent = .2m;
     }
     else if (subtotal >= 250 && subtotal < 500)
     {
       
discountPercent = .15m;
     }
     else if (subtotal >= 100 && subtotal < 250)
     {
       
discountPercent = .1m;
     }
    
// calculate and assign the values for the
     // discountAmount and invoiceTotal variables
     decimal discountAmount = subtotal * discountPercent;
     decimal invoiceTotal = subtotal - discountAmount;

     // format the values and display them in their text boxes
     txtDiscountPercent.Text =     // percent format 
        discountPercent.ToString("p1");                            // with 1 decimal place
     txtDiscountAmount.Text =
        discountAmount.ToString("c");                             // currency format
     txtTotal.Text =
        invoiceTotal.ToString("c");

     // move the focus to the Subtotal text box
     txtSubtotal.Focus();
  }

Description

  • Comments are used to help document what a program does and what the code within it does.
  • To code a single-line comment, type // before the comment. You can use this technique to add a comment on its own line or to add a comment at the end of a line.
  • To code a delimited comment, type /* at the start of the comment and */ at the end. You can also code asterisks to identify the lines in the comment, but that isn’t necessary.

Figure 3-8   How to code comments

How to work with the Text Editor toolbar


 
Figure 3-9 shows how you can use the Text Editor toolbar to work with code. If you experiment with this toolbar, you’ll find that its buttons provide some useful functions for working with comments and indentation and for moving from one place to another.

In particular, you can use the Text Editor toolbar to modify several lines of code at once. For example, during testing, you can use this toolbar to comment out several lines of code by selecting the lines of code and then clicking on the Comment button. Then, you can test the program without those lines of code. If necessary, you can use the Uncomment button to restore those lines of code. Similarly, you can use the Increase Indent and Decrease Indent buttons to adjust the indentation for selected lines of code.

You can also use the Text Editor toolbar to work with bookmarks. After you use the Toggle Bookmark button to mark lines of code, you can easily move between the marked lines of code by using the Next and Previous buttons. Although you usually don’t need bookmarks when you’re working with simple applications like the one shown here, bookmarks can be helpful when you’re working with applications that contain more than a few pages of code.

If you experiment with the other buttons on the Text Editor toolbar, you’ll find that they provide IntelliSense features like the ones you learned about earlier in this chapter for referring to properties, methods, and events. You can use these buttons to force Visual Studio to display a member list or information about a member that’s displayed in the Code Editor.

How to collapse or expand blocks of code
 
As you write the code for an application, you may want to collapse or expand some of the regions, comments, and methods to make it easier to scroll through the code and locate specific sections of code. To do that, you can use the techniques described in figure 3-9. In this figure, for example, the frmInvoiceTotal method has been collapsed so all you can see is its method declaration.

You may also want to collapse or expand code before you print it. Then, in the dialog box for the File->Print command, you can check or uncheck the Hide Collapsed Regions box. If this box is checked, Visual Studio will only print the code that’s displayed in the Code Editor.

The Code Editor and the Text Editor toolbar


Figure 3-9.  How to use the Text Editor toolbar and collapse or expand code

How to use the buttons of the Text Editor toolbar

  • To display or hide the Text Editor toolbar, right-click in the toolbar area and choose Text Editor from the shortcut menu.
  • To comment or uncomment several lines of code, select the lines and click the Comment or Uncomment button. During testing, you can comment out coding lines so they won’t be executed. That way, you can test new statements without deleting the old statements.
  • To increase or decrease the indentation of several lines of code, select the lines and click the Increase Indent or Decrease Indent button. Or, press the Tab and Shift+Tab keys.
  • To move quickly between lines of code, you can use the last eight buttons on the Text Editor toolbar to set and move between bookmarks.

How to collapse or expand regions of code

  • If a region of code appears in the Code Editor with a minus sign (-) next to it, you can click the minus sign to collapse the region so just the first line is displayed.
  • If a region of code appears in the Code Editor with a plus sign (+) next to it, you can click the plus sign to expand the region so all of it is displayed.

How to use code snippets


 
When you add code to an application, you will often find yourself entering the same pattern of code over and over. For example, you often enter a series of if blocks like the ones in the previous figures. To make it easy to enter patterns like these, though, Visual Studio 2005 introduces a new feature known as code snippets. These code snippets make it easy to enter common control structures like the ones that you’ll learn about in chapter 5.

Sometimes, you’ll want to insert a code snippet on a blank line of text as shown in figure 3-10. In that case, you can right-click on the blank line in the Code Editor and select the Code Snippet command from the resulting menu. Then, you can select the shortcut name for the code snippet you wish to insert and press the Tab key. When you do, the code snippet will be inserted into the Code Editor. In this figure, for example, the code snippet named if (not the #if snippet at the top of the list) has been inserted into the document. This snippet contains the start of an if block. Now, you just need to enter a condition within the parentheses and some statements for the if block between the curled braces.

Other times, you’ll want to surround existing lines of code with a code snippet. In that case, you can select the code that you want to surround, right-click on that code, and select the Surround With command from the resulting menu. Then, you can select the appropriate snippet. For example, you might want to add an if block around one or more existing statements.

If you find that you like using code snippets, you should be aware that it’s possible to add or remove snippets from the default list. To do that, you can choose the Code Snippets Manager command from the Tools menu. Then, you can use the resulting dialog box to remove code snippets that you don’t use or to add new code snippets. Be aware, however, that writing a new code snippet requires creating an XML file that defines the code snippet. To learn how to do that, you can consult the documentation for Visual Studio.

Incidentally, if you’re new to programming and don’t understand the if statements in this chapter, don’t worry about that. Instead, just focus on the mechanics of using code snippets. In chapter 5, you’ll learn everything you need to know about coding if statements.

The default list of code snippets


Figure 3-10.  How to use code snippets

A code snippet after it has been inserted

Description

  1. To insert a code snippet, right-click in the Code Editor and select the Code Snippet command from the resulting menu. Then, select the code snippet you wish to insert.
  2. To surround existing code with a code snippet, select the code, right-click on it, and select the Surround With command from the resulting menu. Then, select the appropriate snippet.
  3. You can use the Tools->Code Snippets Manager command to display a dialog box that you can use to edit the list of available code snippets and to add custom code snippets.

Please check back next week for the conclusion of this article.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials