Presentation is loading. Please wait.

Presentation is loading. Please wait.

Developing Windows Applications with Visual Studio Windows Forms Controls and Coding Jim Warren – COMPSCI 280 S2 2015 Enterprise.

Similar presentations


Presentation on theme: "Developing Windows Applications with Visual Studio Windows Forms Controls and Coding Jim Warren – COMPSCI 280 S2 2015 Enterprise."— Presentation transcript:

1 Developing Windows Applications with Visual Studio Windows Forms Controls and Coding Jim Warren – jim@cs.auckland.ac.nz COMPSCI 280 S2 2015 Enterprise Software Development

2 Agenda & Reading COMPSCI2802  Objectives  To learn how VS structures a Windows Forms application. To understand how it uses  Partial classes  Event handlers  To understand use of handy graphical user interface (GUI) controls through examples  DateTimePicker & MessageBox  TabControl  File dialog  Validation  Recommended Reading:  Getting Started with Windows Forms  http://msdn2.microsoft.com/en-us/library/ms229601(VS.80).aspx http://msdn2.microsoft.com/en-us/library/ms229601(VS.80).aspx

3 Windows Form COMPSCI2803  A form is a visual surface on which you display information to the user  A control is a discrete user interface (UI) element that displays data and/or accepts data input  When a user does something to your form or one of its controls, the action generates an event  Your application reacts to these events by using code, and processes the events when they occur  Windows Forms contains a variety of controls that you can add to forms:  Button, CheckBox, RadioButton, and TextBox  ComboBox and ListBox  Panel controls (contain other controls), e.g. TabControl  ToolStrip and MenuStrip (Toolbars and menus that contain text and images, display submenus, and host other controls such as text boxes and combo boxes)  You can also create your own custom controls using the UserControl class

4 Partial class definition  The definition of a single class can be split between multiple source (.cs) files  This is handy for group programming  In VS, each form is a class  It inherits from the Form class  A.cs file with its name (e.g. AddForm.cs) provides a place for you to add code to customize the form’s behaviour  A separate ‘Designer’ file (e.g. AddForm.Designer.cs) holds additional definitions contributed by the visual editor COMPSCI2804 Public partial class AddForm : Form { public AddForm() { InitializeComponent(); }... Addform.cs defining inheritance and constructor, and providing space for user code

5 Partial class definition  For each control you drag onto the form in the visual designer, definition of an object of the appropriate name and class is added automatically in the complementary.Designer file COMPSCI2805 partial class AddForm {... private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.DateTimePicker dateTimePicker1; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label3; 3 labels, 2 textbox text entry controls, a date-time picker and a button

6 Partial class definition  The.Designer file also defines the InitializeComponent method, including  Constructing all the objects on the form  Setting their properties based on how you’ve tailored them visually (and setting properties of the form itself, such as its size)  Specifying that the control objects are in the forms ‘Controls’ collection  Defining event handlers (see subsequent slides) COMPSCI2806

7 InitializeComponent automatic code  In the form’s.Designer.cs file COMPSCI2807 private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox();... this.SuspendLayout();... this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(60, 29); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(69, 17); this.label1.TabIndex = 0; this.label1.Text = "Surname:";... this.ClientSize = new System.Drawing.Size(364, 215);... this.Controls.Add(this.textBox1); this.Controls.Add(this.label1);... this.ResumeLayout(false); this.PerformLayout(); Add to collection of controlled objects Suspend drawing until we’ve set everything up Define any non-default attribute values you set via the Properties window or by dragging and stretching Resumes performing layout, but doesn’t force a redraw (next statement does that)

8 Events of Windows Form COMPSCI2808  When a Windows Forms application starts, the startup events of the main form are raised:  Load  Occurs before a form is displayed for the first time  When an application closes by calling the close(), the shutdown events of the main form are raised:  FormClosing  Occurs as the form is being closed. When a form is closed, it is disposed of, releasing all resources associated with the form  To cancel the closure of a form, set the Cancel property of the FormClosingEventArgs passed to your event handler to true  FormClosed  Occurs after the form has been closed by the user or by the Close method or the Exit method of the Application class  See also http://stackoverflow.com/questions/2683679/how-to-know-user-has- clicked-x-or-the-close-buttonhttp://stackoverflow.com/questions/2683679/how-to-know-user-has- clicked-x-or-the-close-button this.Load += new System.EventHandler(this.Form1_Load); private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; //Cancel closing form

9 Events on forms or controls  The ‘lightening bolt’ icon on the Properties window will show you all the available events for whatever form or control is selected in the visual designer  There are lots (potential for fine-grained control!)  Automatically adds the event handler code in the form’s.cs file and the link of the event handler to control object in the.Designer file COMPSCI2809

10 Event code  In the form’s.cs file  In the.Designer file  Adding click event handlers to buttons is a mainstay of GUI interaction COMPSCI28010 this.MouseLeave += new System.EventHandler(this.MyCustomHandler); private void MyCustomHandler(object sender, EventArgs e) { // do whatever you want when the mouse cursor leaves the form } this.button1.Click += new System.EventHandler(this.button1_Click); private void button1_Click(object sender, EventArgs e) { Employee emp1 = new Employee { GivenNames=textBox2.Text, Surname = textBox1.Text, DateOfBirth=dateTimePicker1.Value }; using (EmployeesContext db = new EmployeesContext()) { db.Employees.Add(emp1); db.SaveChanges(); } this.Close(); }

11 Communication between forms  A form’s just a class so you can give it additional fields or properties that can be set by another form COMPSCI28011 UpdateForm u = new UpdateForm(); int rownum = dataGridView1.SelectedRows[0].Index; u.id = (int)dataGridView1.SelectedRows[0].Cells[0].Value; u.ShowDialog(); public partial class UpdateForm : Form { public int id; public UpdateForm() { InitializeComponent(); } For an update form, we’d want to know which record we’re updating – just give it a field that a calling form can set The parent application can create a new instance of the update form Set the id field based on what record we want to update (see labsheet re dataGridView controls) Run the update form’s Shown event and have it be a ‘modal dialog’ (no other form can get focus until it closes)

12 DateTimePicker & MessageBox COMPSCI28012  The DateTimePicker control allows the user to select a single item from a list of dates or times.  The Value property contains the current date and time the control is set to.  Four formats: which are set by the Format property:  Long (Monday, 27 February 2006), Short (27/02/2006), Time(10:15:48 p.m.), or Custom  To display Time with the DateTimePicker Control  Set the Format property to Time  Set the ShowUpDown property for the DateTimePicker to true.  The MessageBox control displays a message box that can contain text, buttons, and symbols that inform and instruct the user.  MesageBoxButtons: defines the number & caption of the buttons appearing  OK, OKCancel, YesNo, YesNoCancel …  MessageBoxIcon: defines the icon appearing in the message box  Information, question, warning, error …  DialogResult  Cancel, OK, Yes … MessageBox.Show("The selected value is " + DateTimePicker1.Text); DialogResult returnValue = MessageBox.Show(message, title, buttons, icon);

13 The TabControl Control Handout14COMPSCI28013  The Windows Forms TabControl displays multiple tabs, like dividers in a notebook or labels in a set of folders in a filing cabinet.  Each tab page is a container for other controls, much like a mini form!  The most important property of the TabControl is TabPages, which contains the individual tabs.  Other properties:  The SelectedIndex property gets or sets the index of the currently selected tab page.  The SelectedTab property gets or sets the currently selected tab page.  The TabCount property gets the number of tabs in the tab strip.  Methods  The SelectTab method makes the specified tab the current tab.  The DeselectTab method makes the tab following the tab with the specified index the current tab.  Events  Selecting, Selected, Deselecting, Deselected See http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.deselecting.aspxhttp://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.deselecting.aspx

14 The TabControl Control (con’t) COMPSCI28014  To add a tab programmatically  Alternatively, you can add tabs to the TabControl by using the TabPages property at design time  To remove a tab programmatically  To display an icon on the label part of a tab  Add an ImageList control and add images to the image list.  Set the ImageList property of the TabControl to the ImageList control.  Set the ImageIndex property of the TabPage to the index of an appropriate image in the list.  To add a Control to a Tab Page  To add a control programmatically  Use the Add method of the collection returned by the Controls property of a TabPage:  Alternatively, you can add controls to the TabControl at design time TabPage1.Controls.Add(new Button()); TabPage myTabPage = new TabPage("NewPage")); TabControl1.TabPages.Add(myTabPage); TabControl1.TabPages.Remove(TabControl1.SelectedTab);

15 File Common Dialog Boxes  Not unusual for an application to want to allow the user to specify a file or directory for an operation (load, save, etc.)  That’s a pretty tricky dialog, so good that we don’t need to write it from scratch! Instead we can them from the Dialogs part of the toolbox in the VS designer  OpenFileDialog  Prompts the user to open a file.  SaveFileDialog  Prompts the user to select a location for saving a file.  Properties  FileName  Gets/sets a string containing the file name selected in the file dialog box.  Filter  Gets/sets the current file name filter string, which determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box  FilterIndex  Gets/sets the index of the filter currently selected in the file dialog box. COMPSCI28015

16 File Dialog Boxes  Filter String:  Contains a description of the filter, followed by the vertical bar (|) and the filter pattern.  Different filtering options are separated by the vertical bar.  Method: ShowDialog()  Displays the OpenFileDialog or SaveFileDialog box  It returns a value of type DialogResult to indicate whether the user wants to continue the operation Handout14COMPSCI28016 dlgOpen.Filter = "All Files (*.*)|*.*|Text Files (*.txt)|*.txt“; dlgOpen.FilterIndex = 2; Files of Type/Save as Type determined by Filter Property Index:2 Index:1 Starts from 1 instead of 0 (unusual in the C / C# world!) See http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspxhttp://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx

17 The FolderBrowserDialog Control  Represents a common dialog box that allows the user to choose a folder  Properties:  Description  Gets or sets the descriptive text displayed above the tree view control in the dialog box.  RootFolder  Gets or sets the root folder where the browsing starts from.  SelectedPath  Gets or sets the path selected by the user. COMPSCI28017 using (FolderBrowserDialog dlgFolder = new FolderBrowserDialog()) if (dlgFolder.ShowDialog() == DialogResult.OK) txtDirectory.Text = dlgFolder.SelectedPath; }

18 ErrorProvider COMPSCI28018  ErrorProvider presents a simple mechanism for indicating to the end user that a control on a form has an error associated with it.  If an error description string is specified for the control, an icon appears next to the control. The icon flashes in the manner specified by BlinkStyle, at the rate specified by BlinkRate.  When the mouse hovers over the icon, a ToolTip appears showing the error description string.  To Create an ErrorProvider control  Drag and drop the control onto the form  The ErrorProvider is displayed at the component tray at the bottom of the form  To set the error message (e.g. on a TextBox control textBox1)  To clear the error message errorProvider1.SetError(textBox1, ""); errorProvider1.SetError(textBox1, "Not a number!");

19 Validation COMPSCI28019  When a user enters or leaves a field by using the keyboard, the following events occur in order:  Enter (the focus is about to enter the control)  GotFocus (the focus has entered the control)  Leave (the focus is about to leave the control)  Validating (the data in the control is ready to validate)  Validated (the data has been validated)  LostFocus (the focus has left the control)  Note: if you change the focus by using the mouse, the events occur in the following order:  Enter->GotFocus->LostFocus->Leave->Validating->Validated.  You can use the Validating event for validating user input.  If validation fails, you can halt the chain of events and prevent the user from moving on until any error is corrected.  Control.CausesValidaton  If the CausesValidation property of the control is set to false, the Validating and Validated events are suppressed private void TextBox1_Validating(object sender, CancelEventArgs e) {... See http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspxhttp://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx

20 Validating with ErrorProvider COMPSCI28020  To validate input from the user  Create an event handler for the Validating event (use part of component Properties)  Validate the input from the user  If validation fails, display an ErrorProvider, and the event is canceled by setting the Cancel property of the CancelEventArgs to true. All events that would usually occur after the Validating event are suppressed Note:  Closing a form fires the Validating event. If the Cancel property is True in a Validating event, this will prevent the form from closing  You can change it in the Closing event of the form by setting the Cancel property to false string strEntered = textBox1.Text; if (! String.IsNullOrEmpty(strEntered)) { int number = int.Parse(strEntered); if (number < 0) { e.Cancel = true; errorProvider1.SetError(textBox1, "less than zero"); } else{ errorProvider1.Clear(); } Dumb example – throws a FormatException if user enters text

21 Conclusion  Windows Forms is a powerful application template for creating traditional ‘thick client’ Windows applications with a graphical user interface  Uses partial class definition to allow user code in one file and automatically generated code from the visual designer in another  Lots of useful event handlers for fine-grained control and control classes for common interaction tasks  Week 8 labsheet constructs a Windows Forms application working with a database (also exemplifies EF database update functions) COMPSCI28021


Download ppt "Developing Windows Applications with Visual Studio Windows Forms Controls and Coding Jim Warren – COMPSCI 280 S2 2015 Enterprise."

Similar presentations


Ads by Google