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

Slides:



Advertisements
Similar presentations
Information System Design Lab 5&6. User Interface Design.
Advertisements

CS0004: Introduction to Programming Visual Studio 2010 and Controls.
 2007 Dr. Natheer Khasawneh. Chapter 13. Graphical User Interface Concepts: Part 1.
Chapter 1: An Introduction to Visual Basic 2012
Copyright © 2012 Pearson Education, Inc. Chapter 11 MORE WINDOWS CONTROLS & STANDARD DIALOG BOXES.
© by Pearson Education, Inc. All Rights Reserved.
Visual Basic 2010 How to Program. © by Pearson Education, Inc. All Rights Reserved.2.
Visual Basic 2010 How to Program Reference: Instructor: Maysoon Bin Duwais slides Visual Basic 2010 how to program by Deitel © by Pearson Education,
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
C# Programming: From Problem Analysis to Program Design1 9 Programming Based on Events.
Creating Custom Forms. 2 Design and create a custom form You can create a custom form by modifying an existing form or creating a new form. Either way,
C# Programming: From Problem Analysis to Program Design1 Programming Based on Events C# Programming: From Problem Analysis to Program Design 3 rd Edition.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Graphical User Interface (GUI) A GUI allows user to interact with a program visually. GUIs are built from GUI components. A GUI component is an object.
Automating Tasks With Macros. 2 Design a switchboard and dialog box for a graphical user interface Database developers interact directly with Access.
Programming Based on Events
Macros Tutorial Week 20. Objectives By the end of this tutorial you should understand how to: Create macros Assign macros to events Associate macros with.
BİL528 – Bilgisayar Programlama II Advanced Controls, Menus, Toolbars, and Status Bars 1.
Microsoft Visual Basic 2005 ENRICHMENT CHAPTER Visual Studio Tools for Office.
WORKING WITH MACROS CHAPTER 10 WORKING WITH MACROS.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
BIM313 – Advanced Programming Simple Controls 1. Contents Traditional Controls – Labels, Text Boxes, Buttons, Check Boxes, List Boxes, Combo Boxes Advanced.
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
Introduction to Graphical User Interfaces. Objectives * Students should understand what a procedural program is. * Students should understand what an.
Object Oriented Programming Graphical User Interfaces Dr. Mike Spann
Multiple Forms, Container Controls, AddHandler This presentation is based on the Forms and ContainerControls VB Projects 1.
Chapter 12: Using Controls. Examining the IDE’s Automatically Generated Code A new Windows Forms project has been started and given the name FormWithALabelAndAButton.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Typing Application Introducing Keyboard Events, Menus, Dialogs and the Dictionary.
1 Working with Menus and Dialog Boxes. 2 Objectives You will be able to Create and edit menus for Windows Forms applications. Write code to handle menu.
Dr Dat Tran - Week 4 Lecture Notes 1 ToolStrip Programming Graphical User Interfaces PG (7110) University of Canberra School of Information Sciences &
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 13 – Graphical User Interfaces Part 2 Outline.
Graphical User Interface Concepts - Part 2 Session 09 Mata kuliah: M0874 – Programming II Tahun: 2010.
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
COS240 O-O Languages AUBG, COS dept Lecture 33 Title: C# vs. Java (GUI Programming) Reference: COS240 Syllabus.
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
Lecture Set 12 Sequential Files and Structures Part A – Dialog Boxes, Filters, Directories.
BIM211 – Visual Programming Interacting with Users Graphics 1.
1 Chapter Nine Using GUI Objects and the Visual Studio IDE.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
C# GUI - Basics. Objectives.NET supports two types: WinForms, traditional, desktop GUI apps. WebForms – newer, for Web apps. Visual Studio.NET supports.
1 Creating Windows GUIs with Visual Studio. 2 Creating the Project New Project Visual C++ Projects Windows Forms Application Give the Project a Name and.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Application Development Using VB.NET 1 Chapter 10 VB.NET GUI Components Overview.
C# - FCL/Form & Control Validation John Kelleher.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
COMPUTER PROGRAMMING I 3.01 Apply Controls Associated With Visual Studio Form.
Lecture Set 7 Procedures and Event Handlers Part B - The Structure of an Application Event Handlers.
Graphical User Interface Components Version 1.1. Obectives Students should understand how to use these basic Form components to create a Graphical User.
Understand Databound Controls Windows Development Fundamentals LESSON 4.2A.
1 Windows Forms II Chapter RadioButton / GroupBox Controls Used to solicit a multiple choice input. Radio buttons work as a group. Selecting one.
XP New Perspectives on Macromedia Dreamweaver MX 2004 Tutorial 5 1 Adding Shared Site Elements.
COMPUTER PROGRAMMING I 3.01 Apply Controls Associated With Visual Studio Form.
Graphical User Interfaces Part 2 1 Outline TreeViews ListViews Tab Control.
Visual Basic/ Visual Studio Brandon Large. Connecting to prior knowledge In your notes write down what the two main parts of the computer are. The “software”
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Dive Into® Visual Basic 2010 Express
Graphical User Interface
Apply Procedures to Develop Menus, List Box and Combo Box Objects
3.01 Apply Controls Associated With Visual Studio Form
Reference: COS240 Syllabus
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Multi-form applications and dialogs
Part A – Doing Your Own Input Validation with Simple VB Tools
Lecture Set 10 Windows Controls and Forms
Module 8: Creating Windows-based Applications
6. WinForms 2003 C# GUI - Basics.
How to organize and document your classes
Overview of the IDE Visual Studio .NET is Microsoft’s Integrated Development Environment (IDE) for creating, running and debugging programs (also.
Presentation transcript:

Developing Windows Applications with Visual Studio Windows Forms Controls and Coding Jim Warren – COMPSCI 280 S Enterprise Software Development

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 

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

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

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

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

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)

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 clicked-x-or-the-close-buttonhttp://stackoverflow.com/questions/ /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

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

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(); }

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)

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);

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

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);

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

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

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; }

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!");

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

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

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