The last part of this application requires that you to build an editing window to add and edit stocks in the database. This window is shown in Figure 13.3.
Because the bulk of the code for managing stocks is kept in the list window, this window doesn't have much code in it. To get started, you need to add some controls and set some properties on them. For the form, you need to set the following properties:
Property | Value |
---|---|
(Name) | frmEditStock |
Text | ### Stock |
The title of the window will be changed at runtime, depending on whether the window is being used to add a new stock or to edit an existing one. The three pound signs are just there as a visual placeholder.
Next, you need three Label controls and three TextBox controls, as well as two Button controls. For the code you'll write later in the chapter, the following names are used for the controls:
You can arrange the controls as you see fit, but be sure to clear the Text property of each of the TextBox controls so they initially are empty.
With the controls on the form, it's time to add the code to make this window work. The complete listing (including all the hidden code) is shown in Listing 13.2. The code you need to add is highlighted in bold in this listing.
This window will use events to notify its parent when the user has finished either adding a new stock or editing an existing one. This is done through two public events declared in the declarations section of the form. Each event has the same parameters; however, the events are named differently because the action that the list form needs to take is different for an addition versus an edit.
You also declare a Boolean variable to store whether or not the record is being edited. This will determine which event is raised when the user clicks the OK button.
The next code you need is the constructor, or New subroutine, for the form. Normally, the constructor is stored in the “Windows Form Designer” generated code. However, because we'll have two constructors, you need to move the default constructor (the one with no parameters) out of the #Region tag. You'll also create a second constructor that is used to edit a stock. The one with no parameters is used for adding new stocks. Each of these routines populates the boxes on the form, either with the data passed to it from the list window or with default values.
The user is then able to make changes to the values in the form, at which point he or she decides to close the window. Clicking the Cancel button simply closes the window, but clicking the OK button needs to signal the list window of the new or modified stock. The code in the OK button handler takes care of this task. Based on the value in the flag variable, the new data is either sent via the AddComplete or EditComplete events back to the list window. This routine should have some validation in a real world application; however, it's been omitted here for clarity.