1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual C plus plus phần 10 ppt

119 202 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 119
Dung lượng 2,74 MB

Nội dung

::DialogResult result = MessageBox::Show(L”Upper limit: “ + upper + L” Lower limit: “ + lower + L”\nUpper limit must be at least 5 greater that the lower limit.” + L”\nTry Again.”, L”Limits Invalid”, MessageBoxButtons::OKCancel, MessageBoxIcon::Error); if(result == ::DialogResult::OK) DialogResult = ::DialogResult::None; else DialogResult = ::DialogResult::Cancel; } else { upperLimit = upper; lowerLimit = lower; } } Because the third argument to the Show() function is MessageBoxButtons::OKCancel, the message box now has two buttons as shown in Figure 21-23. Figure 21-23 In the Click event handler for the OK button in the limits dialog box you store the return value from the Show() function in result. The type for result has to be specified using the scope resolution operator. Otherwise, it is interpreted by the compiler as the DialogResult property for the lottoLimitsDialog object, and the code does not compile. If result contains the value ::DialogResult::OK, you set the DialogResult property for the lottoLimitsDialog object to ::DialogResult::None, which prevents the dialog box from closing and allows the limit to be changed. Otherwise you set the DialogResult property for the dialog to ::Dialog::Cancel, which has the same effect as clicking the Cancel button for the dialog box so it closes. 1066 Chapter 21 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1066 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Handler the Reset Menu Item Event You can implement the event handler for the Reset menu item like this: System::Void resetMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { if(lottoTab->Visible) { // Reset user limits for Lotto lottoUserMaximum = lottoUpperLimit; lottoUserMinimum = lottoLowerLimit; lottoLimitsDialog->UpperLimit = lottoUpperLimit; lottoLimitsDialog->LowerLimit = lottoLowerLimit; } else if(euroTab->Visible) { // Reset user limits for Euromillions euroUserMaximum = euroUpperLimit; euroUserMinimum = euroLowerLimit; euroStarsUserMaximum = euroStarsUpperLimit; euroStarsUserMinimum = euroStarsLowerLimit; // Code to update Euromillions limits dialog } } This just resets the limits in the fields in the Form1 object and then updates the properties in the dialog object accordingly. You still have to add code to this function to deal with resetting the dialog box to which you have yet added the application that will handle the input for the Euromillions lottery limits. You can now recompile the program and try changing the limits for the Lotto entry. A typical application window is shown in Figure 21-24. Figure 21-24 1067 Applications Using Windows Forms 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1067 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com As you see, you automatically get a scrollbar for scrolling through the list of items in a list box. Note that scrolling to a given item does not select it. You must also click on the item to select it before clicking the OK button. Selecting the Limits > Reset menu item resets both limits to their original values. Adding the Second Dialog The second dialog box for setting limits for the Euromillions lottery is going to be easy; it’s the same process as for the first dialog box. Create a new form in the project by pressing Ctrl+Shift+A to display the Add New Item dialog box and select the UI category and the Windows Form template; the name should be EuroLimitsDialog. You can set property values for this dialog box in much the same way as for the previous dialog. Form Property Value to be Set FormBorderStyle FixedDialog ControlBox False MinimizeBox False MaximizeBox False Text Set Euromillions Limits You can add OK and Cancel buttons to the dialog form next. Set the Text property values for the buttons to “OK” and “Cancel” and the (Name) property values to euroOK and euroCancel, respectively. You should also set the DialogResult property values to OK and Cancel. With the buttons defined, you can return to the properties for the dialog form and set the AcceptButton and CancelButton property val- ues to euroOK and euroCancel, respectively. In the interests of getting experience of a wider range of controls, you’ll forego consistency in the appli- cation, and you won’t use ListBox controls to handle the input as you did in the first dialog box. In this dialog box you need to provide for the entry of upper and lower limits for the set of five values as well as the set of two stars. It won’t make for a very elegant implementation, but to maximize the variety of controls you work with you’ll use NumericUpDown controls for the former and ComboBox controls for the latter. You can add these controls together with associated Label controls to the dialog form with each group of controls placed within a GroupBox control, as illustrated in Figure 21-25. Obviously “you’ll need to add the GroupBox controls first and then place the other controls within them. To identify the function of the controls within each group box, the value for the Text property for the upper group box has been set to “Set Values Limits” and that of the lower group box “Set Stars Limits” . You won’t be accessing the GroupBox objects in the code so the (Name) property values for these are of no importance. You can set the value of the Text property for each Label control as shown in Figure 21-25. The values for the (Name) properties for the NumericUpDown controls in the upper group box should be set to lowerValuesLimits and upperValuesLimits. You can set the values that these controls display by setting values for the Maximum and Minimum properties. These values for the lowerValuesLimits control on the left should be 44 and 1 respectively, and the values for the Maximum and Minimum prop- erties for the control to the right should be 49 and 6 respectively. You can set the value of the Value 1068 Chapter 21 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1068 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com property for the upperValuesLimit control to 49; this is the value displayed initially in the control. If you also set the ReadOnly property value for each of the NumericUpDown controls to True, this prevents the entry of a value from the keyboard. You are using the NumericUpDown control very simply here. You can change the up down increment by setting the Increment property value. The Increment property is of type Decimal so you can set this to non-integral values, too. Figure 21-25 You can set the values of the (Name) property for the ComboBox controls in the lower group box to lowerStarsLimits and upperStarsLimits. You can enter values to be displayed in a ComboBox quite easily. Click the small arrow at the top right of the leftmost ComboBox control to display the menu shown in Figure 21-26. Figure 21-26 1069 Applications Using Windows Forms 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1069 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Select the Edit Items menu item at the bottom of the menu to display the dialog window for the String Collection Editor shown in Figure 21-27. Figure 21-27 Figure 21-27 shows the values entered for the ComboBox control on the left. For the ComboBox control on the right you can enter the values from 2 to 9 inclusive. The ComboBox is not ideal for this application because it allows text input as well as selection from a list; you want to have a limit value selected only from the list. The control gets its name, ComboBox, because it combines the function of a ListBox control that allows selection from a list with that of a TextBox control that provides for text input. Getting the Data from the Dialog Controls You’ll get the limit values back from the controls in essentially the same way as you did for the dialog box for Lotto limits. You can add some new data members to the EuroLimitsDialog class to hold the user limit values first: private: int lowerValuesLimit; int upperValuesLimit; int lowerStarsLimit; int upperStarsLimit; To be on the safe side you had better initialize these members in the class constructor: EuroLimitsDialog(void) :lowerValuesLimit(1) ,upperValuesLimit(50) ,lowerStarsLimit(1) ,upperStarsLimit(9) { 1070 Chapter 21 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1070 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com InitializeComponent(); // //TODO: Add the constructor code here // } You’ll also need some public properties defined in the dialog class to make the limits accessible from the application window object: public: property int LowerValuesLimit { int get() { return lowerValuesLimit; } void set(int limit) { lowerValuesLimit = limit; lowerValuesLimits->Value = limit; // Set as selected in NumericUpDown } } property int UpperValuesLimit { int get() { return upperValuesLimit; } void set(int limit) { upperValuesLimit = limit; upperValuesLimits->Value = limit; // Set as selected in NumericUpDown } } property int LowerStarsLimit { int get() { return lowerStarsLimit; } void set(int limit) { lowerStarsLimit = limit; lowerStarsLimits->SelectedItem = limit; // Set as selected in ComboBox lowerStarsLimits->SelectedIndex = // Set index for selected item lowerStarsLimits->FindString(limit.ToString()); } } property int UpperStarsLimit { int get() { return upperStarsLimit; } void set(int limit) { upperStarsLimit = limit; upperStarsLimits->SelectedItem = limit; // Set as selected in ComboBox upperStarsLimits->SelectedIndex = // Set index for selected item upperStarsLimits->FindString(limit.ToString()); } } 1071 Applications Using Windows Forms 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1071 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The get() function for each property returns the value of the corresponding private member of the dialog class. The set() function sets the value of the data member and also updates the control in the dialog box so that the value set becomes the selected value. The SelectedIndex property value is the index to the selected item. You set this using the FindString() function for the ComboBox control that returns the index value for the first occurrence of the argument in the control’s collection of items. The value at this position is displayed initially in the control. Add a Click event handler for the OK button in the EuroLimitsDialog class by double-clicking the button in the Design window. You won’t need to implement a handler for the Cancel button. You can implement the OK button handler like this: System::Void euroOK_Click(System::Object^ sender, System::EventArgs^ e) { ::DialogResult result; // get the limits for values int valuesLower = Decimal::ToInt32(lowerValuesLimits->Value); int valuesUpper = Decimal::ToInt32(upperValuesLimits->Value); if(valuesUpper - valuesLower < 4) // Check for an adequate range { result = MessageBox::Show(this, // Range insufficient so “Upper values limit: “+valuesUpper + // display message box “ Lower values limit: “+ valuesLower+ “\nUpper values limit must be at least 4 greater that the lower limit.”+ “\nTry Again.”, “Limits Invalid”, MessageBoxButtons::OKCancel, MessageBoxIcon::Error); if(result == ::DialogResult::OK) // If message box OK clicked DialogResult = ::DialogResult::None; // prevent dialog from closing else // Messag box Cancel clicked DialogResult = ::DialogResult::Cancel; // so close the dialog return; } // Get stars limits int starsLower = lowerStarsLimits->SelectedItem == nullptr ? lowerStarsLimit : Int32::Parse(lowerStarsLimits->SelectedItem->ToString()); int starsUpper = upperStarsLimits->SelectedItem == nullptr ? upperStarsLimit : Int32::Parse(upperStarsLimits->SelectedItem->ToString()); if(starsUpper - starsLower < 1) // Check for an adequate range { result = MessageBox::Show(this, // Range insufficient so “Upper stars limit: “+starsUpper + // so display message box “ Lower stars limit: “+ starsLower+ “\nUpper stars limit must be at least 1 greater that the lower limit.”+ “\nTry Again.”, “Limits Invalid”, 1072 Chapter 21 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1072 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com MessageBoxButtons::OKCancel, MessageBoxIcon::Error); if(result == ::DialogResult::OK) // If message box OK clicked DialogResult = ::DialogResult::None; // prevent dialog from closing else // Message box Cancel clicked DialogResult = ::DialogResult::Cancel; // so close the dialog } // Store the new limits lowerValuesLimit = valuesLower; upperValuesLimit = valuesUpper; lowerStarsLimit = starsLower; upperStarsLimit = starsUpper; } The Value property for a NumericUpDown control returns a value of type Decimal. To convert this to type Int32 you pass it as the argument to the static ToInt32() function in the Decimal class. The value that this function returns is automatically unboxed so that it can be stored in the variable of type int. The value returned by the SelectedItem property for a ComboBox control is of type Object^, so to be on the safe side you check whether it is null. If it is null, you set the local variable to the current value recorded in the dialog object; if it isn’t null, you store the value represented by the SelectedItem prop- erty. You can’t store the value directly, but calling the ToString() function for the object produces a string representation of the object that you are then able to convert to type int using the static Parse() function in the Int32 class. You will need a private member of the Form1 class that stores a handle to the new dialog box: private: EuroLimitsDialog^ euroLimitsDialog; // Dialog to set Euromillions limits You can add the following statements to the end of the code in the Form1 class constructor to create the dialog object and update the properties for the stars limit values: euroLimitsDialog = gcnew EuroLimitsDialog; euroLimitsDialog->LowerStarsLimit = euroStarsLowerLimit; euroLimitsDialog->UpperStarsLimit = euroStarsUpperLimit; By setting the LowerStarsLimit and UpperStarsLimit properties for the dialog object, you ensure that the ComboBox controls show these values when the dialog box is initially displayed. If there is no selected item set for a ComboBox control, it displays nothing initially. Don’t forget to add the #include directive for the EuroLimitsDialog class definition to Form1.h: #include “EuroLimitsDialog.h” Disabling Input Controls When the Limits > Upper menu item is clicked, you want to prevent the input for a lower limit being entered, and when the Limits > Lower menu item is selected, you want to prevent input for an upper limit value. You can add a couple of member functions to the EuroLimitsDialog class to make this possible: 1073 Applications Using Windows Forms 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1073 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com public: // Disables controls for selecting upper limits void SetLowerEnabled(void) { upperValuesLimits->Enabled = false; upperStarsLimits->Enabled = false; lowerValuesLimits->Enabled = true; lowerStarsLimits->Enabled = true; } // Disables controls for selecting lower limits void SetUpperEnabled(void) { upperValuesLimits->Enabled = true; upperStarsLimits->Enabled = true; lowerValuesLimits->Enabled = false; lowerStarsLimits->Enabled = false; } The value of the Enabled property for a control determines whether it is enabled. A true value enables the control, and a value of false disables it so the user cannot interact with it. The SetLowerEnabled() func- tion disables the controls used to enter upper limits and enables those for entry of lower limits. The SetUpperEnabled() function does the reverse. Updating the Limits Menu Item Handlers The last step to complete the support for entering limits for the Euromillions lottery is to update the Click event handlers in the Form1 class for the items in the Limits menu. The handler for the Upper menu item should be modified as follows: System::Void upperMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { ::DialogResult result; if(lottoTab->Visible) { lottoLimitsDialog->SetUpperEnabled(); result = lottoLimitsDialog->ShowDialog(this); if(result == ::DialogResult::OK) { lottoUserMaximum = lottoLimitsDialog->UpperLimit; lottoUserMinimum = lottoLimitsDialog->LowerLimit; } } else if(euroTab->Visible) { euroLimitsDialog->SetUpperEnabled(); result = euroLimitsDialog->ShowDialog(this); if(result == ::DialogResult::OK) { euroUserMaximum = euroLimitsDialog->UpperValuesLimit; euroUserMinimum = euroLimitsDialog->LowerValuesLimit; euroStarsUserMaximum = euroLimitsDialog->UpperStarsLimit; 1074 Chapter 21 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1074 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com euroStarsUserMinimum = euroLimitsDialog->LowerStarsLimit; } } } The local variable result is used in both if statements, so it is now declared at the beginning of the function. After enabling the controls in the dialog box appropriately by calling the SetUpperEnabled() function for the dialog object, you display the dialog box as modal. If the user closes the dialog box by clicking the OK button, you store the results available through the properties of the dialog object. The changes to the handler for the Click event for the Lower menu item are very similar: System::Void lowerMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { ::DialogResult result; if(lottoTab->Visible) { lottoLimitsDialog->SetLowerEnabled(); result = lottoLimitsDialog->ShowDialog(this); if(result == ::DialogResult::OK) { lottoUserMaximum = lottoLimitsDialog->UpperLimit; lottoUserMinimum = lottoLimitsDialog->LowerLimit; } } else if(euroTab->Visible) { euroLimitsDialog->SetLowerEnabled(); result = euroLimitsDialog->ShowDialog(this); if(result == ::DialogResult::OK) { euroUserMaximum = euroLimitsDialog->UpperValuesLimit; euroUserMinimum = euroLimitsDialog->LowerValuesLimit; euroStarsUserMaximum = euroLimitsDialog->UpperStarsLimit; euroStarsUserMinimum = euroLimitsDialog->LowerStarsLimit; } } } The logic here is the same as in the previous handler function. Implementing the Help | About Menu Item This is easy now that you know about the MessageBox class. You can just show a message box when the Help > About menu item is clicked: System::Void aboutToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { MessageBox::Show(L”(c) Copyright Ivor Horton”, L”About A Winning Application”, MessageBoxButtons::OK, MessageBoxIcon::Exclamation); } 1075 Applications Using Windows Forms 24_571974 ch21.qxp 1/20/06 11:47 PM Page 1075 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... http://www.simpopdf.com DataGridView^ gridCntrl = gcnew DataGridView; // Creates the control There are the row headers gridCntrl->Columns[3] refers to a single column gridCntrl->ColumnCount is the number of columns Column0 gridCntrl->RowCount is the number of rows Column1 Column2 Column3 Column4 Row0 Row1 gridCntrl->Rows[2] refers to a single row These are the column headers gridCntrl->Rows references the collection... Figure 22-1 Similarly, the Columns property for the control returns a value of type DataGridViewColumnCollection that you can also index to reference a particular column Rows and columns are indexed from zero The Cells property for a DataGridRowCollection object represents a collection containing the cells in the row, and you can index the Cells property to access a specific cell in a row Figure 22-1... Design capability and by setting properties for components used in the project 109 1 Chapter 22 Simpo The data in a DataGridView control is displayed in a rectangular array of cells that you can envisage as a collection of rows or as a collection of columns Each column of cells has a header cell at the top that typically contains text that identifies it, and each row has a row header cell at the beginning, ... values that specify the appearance of a row of cells, or a column of cells, or all the cells in the control, and these can all be in effect concurrently Clearly, because a row and column always intersect, all three of these possibilities apply to any given cell, so you have an apparent conflict Each cell in a DataGridView control is represented by a System::Windows::Forms::DataGridViewCell object, and the... a Controls property that returns a reference to an object of type Control::ControlCollection that represents the collection of controls in the group box The Control::ControlCollection class defines the Contains() function that returns true if the control that you pass as the argument is within the collection and false otherwise Thus you have a way to determine to which group of buttons the button causing... the column DataGridViewCheckBoxColumn This type is used when you want to store bool values (System::Boolean objects) or System::Windows::Forms::CheckState objects as checkboxes in the cells in the column Table continued on following page 109 5 Chapter 22 DataGridViewComboBoxColumn This type is used when you want to display a drop-down list in each cell in the column DataGridViewImageColumn You select... of code generated to represent a data source; certainly, tens of thousands of lines of code are not uncommon in a practical context The classes I have identified in the previous table are solely to encapsulate data from a data source; they do not provide the mechanism for connecting to a data source such as a database and accessing the data within it That capability is provided by a component class called... control object ❑ The AlternatingRowsDefaultCellStyle property for the control object; this applies only to cells in rows with odd index numbers ❑ The RowsDefaultCellStyle property for the control object ❑ The DefaultCellStyle property for the DataGridViewColumn object that contains the cell You would typically access a DataGridViewColumn object by indexing the Columns property for the control object... DataGridViewCellStyle that has the following properties: Property Description BackColor The value is a System::Drawing::Color object that determines the background color of a cell The Color class defines a range of standard colors as static members The default value is Color::Empty ForeColor The value is a Color object that determines the foreground color of a cell The default value is Color::Empty SelectionBackColor... collection of rows Row2 Row3 gridCntrl->Columns references the collection of columns gridCntrl->Rows[2]>Cells[3] references the 4th cell in the 3rd row Figure 22-1 You reference rows and columns of cells through properties of the DataGridView control object The Rows property returns a value of type DataGridRowCollection that is a collection of all the rows, and you refer to a particular row using an index, . the user clicked Cancel in the message box, in which case you set the DialogResult property for the dialog object to ::DialogResult::Cancel, which has the same effect as clicking the Cancel button. GroupBox class has a Controls property that returns a reference to an object of type Control::ControlCollection that represents the collection of controls in the group box. The Control::ControlCollection. original click on the button and you can create this by double-clicking buttonContextMenu in the Design pane for Form1. You can complete the code for the handler function that is created like

Ngày đăng: 12/08/2014, 10:21

TỪ KHÓA LIÊN QUAN