/
Based on  Murach  Chapter 10 Based on  Murach  Chapter 10

Based on Murach Chapter 10 - PowerPoint Presentation

cheryl-pisano
cheryl-pisano . @cheryl-pisano
Follow
342 views
Uploaded On 2019-11-08

Based on Murach Chapter 10 - PPT Presentation

Based on Murach Chapter 10 C10 Slide 1 More skills for working with Windows forms and controls Objectives C10 Slide 2 Applied Given the specifications for a form that uses any of the controls presented in this chapter design and code the form ID: 764513

box form c10 slide form box slide c10 property dialog code add user button combo item select dialogresult payment

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Based on Murach Chapter 10" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Based on Murach Chapter 10 C10, Slide 1 More skills for working with Windows forms and controls

Objectives C10, Slide 2 Applied Given the specifications for a form that uses any of the controls presented in this chapter, design and code the form. Given a form with two or more controls, set the tab order of the controls using the Tab Order view of the form.Given the specifications for an application that displays custom or standard dialog boxes, design and code the application.KnowledgeIn general terms, describe the use of these controls: combo box, list box, radio button, check box, and group box.Explain how the refactoring feature helps you change some of the occurrences of the form name in the code when you rename the file for the form, but not the occurrences in the event handlers for the form.Describe the way the Program class for an application displays the first form of an application.Describe how you can use the DialogResult enumeration and the Tag property to pass data between a form and a custom dialog box.Describe how you can use the FormClosing event to stop a form from closing.

A form with five more types of controls C10, Slide 3

A form with five more types of controls 4A combo box lets the user select one option from a drop-down list of items. A combo box can also let the user enter text into the text box portion of the combo box.A list box lets the user select one or more options from a list of items. If a list box contains more items than can be displayed at one time, a vertical scroll bar is added automatically.Radio buttons let the user select one option from a group of options.A group box can group related controls. For example, it’s common to place related radio buttons within a group box. Then, the user can only select one of the radio buttons in the group.A check box lets the user select or deselect an option.

Common members of list box and combo box controlsC10, Slide 5 Property Description SelectedIndexThe index of the selected item. Items are numbered from 0. If no item is selected, this property has a value of -1.SelectedItemThe object of the selected item.TextThe text value for the selected item.SortedIf set to true, the items in the list are sorted alphabetically in ascending order.ItemsProvides access to the collection of items.

Common members of list box and combo box controls (cont.) C10, Slide 6 Property DescriptionDropDownStyleDetermines whether the user can enter text in the text portion that’s at the top of a combo box. If this property is set to DropDownList, the user must select an item from the list. If this property is set to DropDown, the user can enter data in the text box portion of the combo box.SelectionModeDetermines whether the user can select more than one item from a list box. If this property is set to One, the user can only select one item. If it’s set to MultiSimple or MultiExtended, the user can select multiple items.

Common members (Events) of list box and combo box controls (cont.) C10, Slide 7EventDescriptionSelectedIndexChangedOccurs when the user selects a different item from the list.TextChangedOccurs when the user enters a value into the text box portion of a combo box.

Common properties of the Items collection C10, Slide 8 Indexer Description[index]Gets or sets the item at the specific index in the listPropertyDescriptionCountGets the number of items in the list.MethodDescriptionAdd (object)Adds the specified item to the list.Insert (index, object) Inserts an item into the list at the Specified index.Remove (object)Removes the specified item from the list.RemoveAt (index)Removes the item at the specified index from the list.Clear() Removes all items from the list.

Code that loads a combo box with months (foreach) C10, Slide 9 Add combo box or list box to a form and set its properties, foreach loop to load the name of each month in an array into a combo box. Each time through the loop, the Add method is used to add a month name to the Items collection for this combo box. The first item in the array that’s loaded into the list indicates that the user should select a month from the list (instructions to the user.)string[] months = {"Select a month...", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; foreach (string month in months){ cboExpirationMonth. Items.Add(month); } You need to include additional code when you use this technique to be sure that the user selects an item other than the one that provides instructions.

Code that loads a combo box with years (integers) using while loopC10, Slide 10 int year = DateTime.Today.Year;int endYear = year + 8;cboExpirationYear.Items.Add("Select a year...");while (year < endYear){ cboExpirationYear.Items.Add(year); year++;}

Code that clears and loads a list box of credit cards C10, Slide 11 lstCreditCardType.Items.Clear(); //cleanlstCreditCardType.Items.Add("Visa");lstCreditCardType.Items.Add("Mastercard");lstCreditCardType.Items.Add("American Express");lstCreditCardType.SelectedIndex = 0; //first //item selected It is common to put code that loads a combobox or list box in the event handler for the Load event of the form . That way, the control is loaded when the form is loaded. After that, the user can select an item from the combo box or list box and other methods can get information about that item.

Statements that get information from a combo box or list box (4 ways) //get the index of the item that’s currently selected in the Years combo box. int expYearIndex = cboExpirationYear.SelectedIndex;// to get the value that’s displayed in the textbox portion of this combo box. string expYearText = cboExpirationYear.Text;// Notice that because the SelectedItern property returns an object type, you must cast this object to the appropriate data type to get the value of the item. int expYearValue = ( int ) cboExpirationYear.SelectedItem ; //Or string expMonthValue = cboExpirationMonth.Items [1]. ToString (); 12 string

Code that works with a combo box of names .string [] names={" Judy Taylor","Anne Boehm","Kelly Slivkoff"};foreach (string name in names){ cboNames.Items.Add(name);}cboNames.Items.Insert (0, "Joel Murach"); cboNames. Items.RemoveAt (3 ); cboNames.SelectedIndex = -1; // don't select an item. No //value selected 13

A group box that contains two radio buttonsC10, Slide 14 Common property of radio button and check box controlsCommon event of radio button and check box controls

Code that sets the value of a radio button and check box C10, Slide 15 rdoCreditCard. Checked = true;chkDefault.Checked = true;Code that checks the value of a radio buttonprivate void rdoCreditCard_CheckedChanged(object sender,EventArgs e){ if (rdoCreditCard.Checked == true) EnableControls(); else DisableControls (); } Code that gets the value of a check box bool isDefaultBilling = chkDefault. Checked ;

Summary 16 To determine whether a radio button or check box is checked, you test its Checked property.You can use a group box to group controls. Group boxes are typically used to group controls like radio buttons that function as a group.To add controls to a group box, drag them from the Toolbox into the group box. If you’ve already added the controls you want to include in the group box to the form, just drag them into the group box.Any radio buttons that aren’t placed within a group box function as a separate group.If you move a group box, all of the controls it contains move with it.

A form in Tab Order view before and after the tab order is changedC10, Slide 17

How to use Tab Order view C10, Slide 18

MSDN Library (view->other window ->command window Ctrl+W, A) 19

help command Help for the DateTimePicker control 20

Multi-form Projects. The Add New Item dialog box C10, Slide 21

How to add a new form C10, Slide 22 Display the Add New Item dialog box by selecting the Project  Add New Item command. Or, select the AddNew Item command from the shortcut menu that’s displayed when you right-click on the project in the Solution Explorer.To add a new form, select the Windows Form template from the Add New Item dialog box, enter a name for the form, and click the Add button. It os recommend you use the prefix frm so it’s clear that the file contains a form.

How to add an existing form C10, Slide 23 Display the Add Existing Item dialog box by selecting the ProjectAdd Existing Item command. Or, select the AddExisting Item command from the shortcut menu for the project.To add an existing form, select the cs file for the form from the Add Existing Item dialog box and then click the Open button.If the form is in a different namespace than the other forms in the project, you will need to either change the namespace for the form or add a using directive for the namespace to each form that refers to it.To change the namespace for a form, display the code for the form and then change the name on the namespace statement near the top of the code using refactoring.

Renaming Included Existing Form with different Namespace 24

Renaming Included Existing Form with different Namespace 25

The generated code for a new form named frmPayment C10, Slide 26 For the frmPayment.cs filenamespace Payment{ public partial class frmPayment : Form { public frmPayment() { InitializeComponent (); } } } For the frmPayment.Designer.cs file namespace Payment { partial class frmPayment { #region Windows Form Designer generated code } }

The code that’s generated for the Load event handler of the form C10, Slide 27 The method declaration in the frmPayment.cs file (double click on the form)private void frmPayment_Load(object sender, EventArgs e){ // code that handles the event goes here}The wiring in the frmPayment.Designer.cs filethis.Load += new System.EventHandler ( this. frmPayment _Load );

A project that contains two forms C10, Slide 28

How to change the name of a form C10, Slide 29 Right-click the form in the Solution Explorer and select the Rename command. Or , select the form in the Solution Explorer and press F2. Enter the new name for the form. When you do, Visual Studio asks if you want to rename all references to the file. In most cases, that’s what you’ll want to do.How to change the name of any event handlers for a form’s events Highlight the name of the form in the method that’s used by the event handler, then right-click on the name and choose Rename from the shortcut menu that’s displayed.Enter the new name for the form and click the Apply button in the Rename dialog box.

Starting Different Forms (and multiple Main in Console)30 By default, a project will contain a single Main method, and that method will be stored in the Program class. However, it’s possible to add additional Main methods to your project either accidentally or on purpose. In that case, your application may use the wrong Main method when it starts. To solve this problem, you can delete the Main methods that you don’t want to use. Or, you can display the Project Properties window by selecting the Properties command from the Project menu. Then, you can use that dialog box to specify the class that contains the Main method you want to use. To do that, you display the Application tab and select the class from the Startup Object combo box, which lists all the objects that contain Main methods.

Code that defines the main entry point for an application C10, Slide 31 using System; using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms; namespace Payment{ static class Program { /// <summary> /// The main entry point for the application. /// </summary> [ STAThread ] static void Main() { Application.EnableVisualStyles (); Application.SetCompatibleTextRenderingDefault (false); Application.Run (new frmCustomer () ); } } }

Modal Forms 32When designing applications that contain two or more forms, it’s common to display a form as a dialog box. A form that’s displayed as a dialog box can also be called a modal form. (next 2 slides) This form is displayed when the user clicks the Select Payment button in the Customer form.When you create a form that will be displayed as a dialog box, set properties settings to prevent the user from changing the size of the form or from closing the form other than by using the controls you provide on the form. Although setting the ControlBox property to false removes the Maximize button from a form, the user can still maximize the form by double-clicking its title bar. That’s why you should also set the MaximizeBox property to false.

The Payment form displayed as a dialog box C10, Slide 33 private void btnSelectPayment_Click(object sender, EventArgs e){ Form paymentForm = new frmPayment(); DialogResult selectedButton = paymentForm.ShowDialog(); if (selectedButton == DialogResult.OK) { lblPayment.Text = (string) paymentForm.Tag; } }

Preserve Size Properties for creating custom dialog boxes 34

Code that creates and displays a custom dialog box Form paymentForm = new frmPayment();paymentForm.ShowDialog();// execution continues here after the user responds // to the dialog box

Modeless Forms paymentForm.Show(); //both form be accessed simultaneously C10, Slide 36

Passing Data Between a Form and a Custom Dialog Box 37Get a user response to a custom dialog box from the form that displays it, and it shows how to use the Tag property of a dialog box to make data available to the form that displays it. When you display a form as a dialog box, the ShowDialog method returns a value that indicates how the user responded to the dialog box. This result is determined by the value of the DialogResult property of the form, which can be set to any of the members of the DialogResult enumeration. The first statement shown here, for example, sets the DialogResult property to DialogResult.OK. As soon as this property is set, control returns to the main form.

An enumeration that works with dialog boxes. The Tag PropertyC10, Slide 38 Enumeration Members Property DescriptionThe Tag property holds a reference to an object type, which means that it can hold any type of data.EnumerationMembersDialogResultOK, Cancel, Yes, No, Abort, Retry, Ignore, NonePropertyDescriptionTag Gets or sets data associated with the form or a control. The Tag property

A statement that sets the Tag property of a form frmPayment C10, Slide 39private void SaveData(){string msg = null;if (rdoCreditCard.Checked == true){ msg += "Charge to credit card." + "\n\n"; . . . } else { msg += "Send bill to customer." + "\n\n" ; . . . // A statement that sets the Tag property of a form this .Tag = msg ; //A statement that sets the DialogResult property of a form this .DialogResult = DialogResult .OK ; }

Code that uses the result of a dialog box and the Tag property frmCustomerC10, Slide 40Form paymentForm = new frmPayment();DialogResult selectedButton = paymentForm.ShowDialog();if (selectedButton == DialogResult. OK ) { lblPayment.Text = paymentForm. Tag .ToString (); }

How to use the DialogResult enumeration C10, Slide 41 The DialogResult enumeration provides members that represent the values that a dialog box can return. The ShowDialog method returns a member of this enumeration.You specify the result value of a custom dialog box by setting its DialogResult property. Or, you can set the DialogResult property of a button in the dialog box. Then, when the user clicks that button, the DialogResult property of the form is set accordingly.If you set the CancelButton property of a form to a button on that form, the DialogResult property of that button is automatically set to Cancel.After you set the DialogResult property of a dialog box, the form is closed and control is returned to the form that displayed it. If you close a dialog box without setting the DialogResult property, a value of Cancel is returned to the main form.

How to use the Tag propertyC10, Slide 42 The Tag property provides a convenient way to pass data between forms in a multi-form application.A dialog box can set its Tag property before it returns control to the main form. Then, the main form can get the data from this property and use it as necessary.Because the Tag property is an object type, you must explicitly cast it to the appropriate type to retrieve the data it contains. Or, you can use the ToString method to convert the data to a string.

The syntax for the Show method of the MessageBox class C10, Slide 43MessageBox.Show(text[, caption[, buttons[, icon [, defaultButton]]]]);The enumerations that work with the MessageBox class

A statement that displays a dialog box and gets the user responseC10, Slide 44 DialogResult button = MessageBox.Show( "Are you sure you want to save this data?", "Payment", MessageBoxButtons.YesNo , MessageBoxIcon.Question , MessageBoxDefaultButton.Button2 ); The dialog box that’s displayed

A statement that checks the user response C10, Slide 45 if (button == DialogResult.Yes ) { SaveData(); isDataSaved = true;}

The code for a dialog box that cancels the Closing event C10, Slide 46 private void frmCustomer_FormClosing(object sender, FormClosingEventArgs e){ if (isDataSaved == false) { string message = "This form contains unsaved data.\n\n" + "Do you want to save it?";   DialogResult button = MessageBox.Show (message, "Customer", MessageBoxButtons.YesNoCancel , MessageBoxIcon.Warning );   if (button == DialogResult.Yes ) { if ( IsValidData ()) this.SaveData (); else e.Cancel = true; } if (button == DialogResult.Cancel ) { e.Cancel = true; } } } Open form in design view, open properties window or press F4, click event toolbar button to view events on Form object, find FormClosing event in Behavior group, and double click it.

The dialog box that’s displayed C10, Slide 47

The Customer form C10, Slide 48

Two versions of the Payment dialog box C10, Slide 49 Note: no actual saving (should be in DB)

The property settings for the Customer form C10, Slide 50

The property settings for the Payment form C10, Slide 51

The property settings for the Payment form C10, Slide 52

The code for the Customer form C10, Slide 53

Wiring DataChange 54

frmCustomer Code 55After the code that Visual Studio has generated for the form, a Boolean variable named isDataSaved is declared and set to true. This variable indicates whether the data that’s currently displayed in the form has been saved. It’s set to false any time the data in the Customer Name combo box or the Payment label changes. To accomplish that, both the SelectedIndexChanged event of the combo box and the TextChanged event of the label are wired to the DataChanged method.When the Customer form is loaded, the event handler for the Load event adds two names to the Customer Name combo box. In a production application, of course, the combo box would include many more names, and they would be loaded from a file or database. But for the purposes of this chapter, two names are sufficient. When the user clicks the Select Payment button, the Click event handler for that button displays the Payment form as a dialog box. Then, if the user clicks the OK button in that dialog box, the payment data is displayed in the PaymentMethod label on the Customer form. As you can see, this data is stored in the Tag property of the Payment form.

frmCustomer Code 56If the user clicks the Save button, the Click event handler for that button calls the IsValidData method. This method checks that the user has selected a customer and entered a payment. If so, the event handler for the Click event of the Save button calls the SaveData method. This method sets the SelectedIndex property of the Customer Name combo box to -1 so that no customer is selected, and it clears the Payment Method label. Then, it sets the isDataSaved variable to true and moves the focus to the combo box. In a production application, this data would be saved to a file or database.

The code for the Customer form (cont.) C10, Slide 57

Properties frmCustomer (again) 58

Properties frmPayment (again) 59

The code for the Customer form (cont.) C10, Slide 60 private void SaveData(){cboNames.SelectedIndex = -1;lblPayment.Text = "";isDataSaved = true;cboNames.Focus();}private bool IsValidData(){if (cboNames.SelectedIndex == -1) {MessageBox.Show( "You must select a customer." , "Entry Error" ); cboNames.Focus (); return false ; } if ( lblPayment.Text == "" ) { MessageBox .Show ( "You must enter a payment." , "Entry Error" ); return false ; } return true ; }

The code for the Customer form (cont.) C10, Slide 61 private void frmCustomer_FormClosing(object sender, FormClosingEventArgs e){if (isDataSaved == false){string message ="This form contains unsaved data.\n\n" +"Do you want to save it?";DialogResult button = MessageBox.Show(message, "Customer" , MessageBoxButtons .YesNoCancel , MessageBoxIcon .Warning ); if (button == DialogResult .Yes ) { if ( IsValidData ()) this .SaveData (); else e.Cancel = true ; } if (button == DialogResult .Cancel ) { e.Cancel = true ; } } }

The code for the Payment form C10, Slide 62 After the code that Visual Studio has generated for the form, a Boolean variable named isDataSaved is declared and set to true. This variable indicates whether the data that’s currently displayed in the form has been saved. It’s set to false any time the data in the Customer Name combo box or the Payment label changes. To accomplish that, both the SelectedIndexChanged event of the combo box and the TextChanged event of the label are wired to the DataChanged method. When the Customer form is loaded, the event handler for the Load event adds two names to the Customer Name combo box. In a production application, of course, the combo box would include many more names, and they would be loaded from a file or databaseWhen the user clicks the Select Payment button, the Click event handler for that button displays the Payment form as a dialog box. Then, if the user clicks the OK button in that dialog box, the payment data is displayed in the PaymentMethod label on the Customer form. As you can see, this data is stored in the Tag property of the Payment form.

The code for the Payment formC10, Slide 63 private void Payment_Load(object sender, EventArgs e){lstCreditCardType.Items.Add("Visa");lstCreditCardType.Items.Add("Mastercard");lstCreditCardType.Items.Add("American Express");lstCreditCardType.SelectedIndex = 0;string[] months = { "Select a month...", "January", "February" , "March" , "April" , "May" , "June" , "July" , "August" , "September" , "October" , "November" , "December" }; foreach ( string month in months) { cboExpirationMonth.Items.Add (month ); } cboExpirationMonth.SelectedIndex = 0; int year = DateTime .Today.Year ; int endYear = year + 8; cboExpirationYear.Items.Add ( "Select a year..." ); while (year < endYear ) { cboExpirationYear.Items.Add (year ); year ++; } cboExpirationYear.SelectedIndex = 0; }

The code for the Payment form (cont.) C10, Slide 64 private bool IsValidData(){if (rdoCreditCard.Checked){if (lstCreditCardType.SelectedIndex == -1){MessageBox.Show("You must select a credit card type.", "Entry Error");lstCreditCardType.Focus();return false;} if (txtCardNumber.Text == "" ) { MessageBox .Show ( "You must enter a credit card number." , "Entry Error" ); txtCardNumber.Focus (); return false ; } if ( cboExpirationMonth.SelectedIndex == 0) { MessageBox .Show ( "You must select a month." , "Entry Error" ); cboExpirationMonth.Focus (); return false ; } if ( cboExpirationYear.SelectedIndex == 0) { MessageBox .Show ( "You must select a year." , "Entry Error" ); cboExpirationYear.Focus (); return false ; } } return true ; }

The code for the Payment form (cont.) C10, Slide 65 private void SaveData () { string msg = null; if (rdoCreditCard.Checked == true) { msg += "Charge to credit card." + "\n\n"; msg += "Card type: " + lstCreditCardType.Text + "\n"; msg += "Card number: " + txtCardNumber.Text + "\n"; msg += "Expiration date: " + cboExpirationMonth.Text + "/" + cboExpirationYear.Text + "\n"; } else { msg += "Send bill to customer." + "\n\n"; }   bool isDefaultBilling = chkDefault.Checked ; msg += "Default billing: " + isDefaultBilling ;   this.Tag = msg ; this.DialogResult = DialogResult.OK ; }  

The code for the Payment form (cont.) C10, Slide 66 private void Billing_CheckedChanged (object sender, EventArgs e) { if (rdoCreditCard.Checked) EnableControls(); else DisableControls(); }  private void EnableControls () { lstCreditCardType.Enabled = true; txtCardNumber.Enabled = true; cboExpirationMonth.Enabled = true; cboExpirationYear.Enabled = true; }   private void DisableControls () { lstCreditCardType.Enabled = false; txtCardNumber.Enabled = false; cboExpirationMonth.Enabled = false; cboExpirationYear.Enabled = false; } }

Exercise 10-2 Enhance the Future Value application C10, Slide 67 Add a combo box and a list box to the Future Value application.

Extra 10-1 Convert lengths C10, Slide 68

Extra 10-2 Process lunch orders C10, Slide 69

Extra 10-3 Add a second form to an Invoice Total applicationC10, Slide 70

Project 2-2 Maintain student scores C10, Slide 71

Project 2-2 Maintain student scores (cont.) C10, Slide 72

Project 2-2 Maintain student scores (cont.) C10, Slide 73