Create the Update Command Method

Purpose:

To create a method that will return a SqlCommand object that will be used to update one or more records into a table.

Starting Point:

You have VisualStudio.NET open.  You are creating the RegionHelper command class in the Data Access project.  The code generated by the Data Adapter Wizard while it was generating the stored procedures for the Region table should be readily available.  The Select and Select All command methods for the class should be complete.

Steps:

  1. Copy the method ‘theSelectAllCommand’ that you completed earlier, and paste the copy in just below the original.
  2. Change the name of the new method to ‘theUpdateCommand’.
  3. Change the CommandText property of the SqlCommand object to ‘RegionUpdateCommand’ (you may cut and paste this information from the wizard-generated code.  It will be located in the section of the InitializeComponent under the line that says ‘//  sqlUpdateCommand1)
  4. In the sqlUpdateCommand1 section of the wizard-generated code, you will find all of the update command object’s parameter declarations.  Copy each line of code that begins ‘this.sqlUpdateCommand1.Parameters’.  Paste it in your new function over the single parameter declaration that came over when you copied the select all command method.
  5. Replace all instances of ‘this.sqlUpdateCommand1’ with ‘thisSqlCommand’.
  6. Optional:  Eliminate the extended names in favor of simple names.  For example, the using clauses at the start of the helper class lets you eliminate ‘System.Data.SqlClient.SqlParameter’ in favor of ‘SqlParameter’.  This is not necessary, but it will significantly reduce the wordiness of the code and make it more readable.
  7. That should be all you need to do.  The code for this method is not shown below because it is really ugly and unreadable in this medium, but you can find it in the sample Region Helper class provided.
  8. Compile and save.

Rationale:

This command method is created before the Insert and Delete methods because those methods are subsets of the Update command.  Therefore, creating this method first will save time and minimize errors.

Discussion:

This is the most complex of the standard command procedures, but you can see the process for creating it is not that complex.  It follows the pattern of our earlier command functions, and the only complexity is that there are more long, ugly parameter lines.  Fortunately, the Data Adapter Wizard has once again saved us from the tedium of actually having to write that code.

Previous Step: Create the Select All Command Method

Next Step: Create the Insert Command Method