1
C# and .NET (1) – cont’d
Acknowledgements and copyrights: these slides are a result of combination of notes and slides with contributions from: MichaelKiffer, Arthur Bernstein, Philip Lewis, Hanspeter Mφssenbφck, Hanspeter Mφssenbφck, Wolfgang Beer, Dietrich Birngruber,
Albrecht Wφss, Mark Sapossnek, Bill Andreopoulos, DivakaranLiginlal, Michael Morrison, Anestis Toptsis, Deitel and Associates,
Prentice Hall, Addison Wesley, Microsoft AA.
They serve for teaching purposes only and only for the students that are registered in CSE4413 and should not be published as a book or in any form of commercial product, unless written permission is
obtained from each of the above listed names and/or organizations.
2
C# Namespaces• Namespace
– A group of classes and their methods• No two classes in the same namespace may have the
same name• Classes in different namespaces may have the same
name• The Framework Class Library (FCL) is composed of
namespaces• Namespaces are stored in .dll files called assemblies• A list of the FCL namespaces are shown next• Included in a program with the using keyword
3
C# NamespacesNamespace Description System Contains essential classes and data types (such as int,
double, char, etc.). Implicitly referenced by all C# programs.
System.Data Contains classes that form ADO .NET, used for database access and manipulation.
System.Drawing Contains classes used for drawing and graphics. System.IO Contains classes for the input and output of data, such as with
files. System.Threading Contains classes for multithreading, used to run multiple parts
of a program simultaneously. System.Windows.Forms Contains classes used to create graphical user interfaces. System.Xml Contains classes used to process XML data.
Some of the namespaces of the Framework Class Library
4
How to create a namespace
• Create a class library project (in VS.NET) (File -> New -> New Project -> [C# Projects selected in Project types] -> Class Library).
• Make sure that ‘namespace TimeLibrary’ is included in the beginning of the generated file. (as shown in next slide).
6
How to create a namespace, cont’d
• Type your code for the class (you may rename the class, as you like).
• Compile the code with the ‘Build Solution’ option (Build-> Build Solution).
• This code cannot be executed since it doesn’t contain Main(), but it will generate a .dll file, named TimeLibrary.dll, found in the bin\Debug directory under your project directory (TimeLibrary). This .dll file is the Assembly and it can then be included in your applications (by typing ‘using TimeLibrary’ at the beginning of your files.
7
AssemblyTest.cs
Program Output
1 // AssemblyTest.cs2 // Using class Time3 from assembly TimeLibrary.3 4 using System;5 using TimeLibrary;6 7 // AssemblyTest class definition8 class AssemblyTest9 {10 // main entry point for application11 static void Main( string[] args )12 {13 Time3 time = new Time3( 13, 27, 6 );14 15 Console.WriteLine( 16 "Standard time: {0}\nUniversal time: {1}\n",17 time.ToStandardString(), time.ToUniversalString() );18 }19 }
Standard time: 1:27:06 PMUniversal time: 13:27:06
Reference the TimeLibrarynamespace
Use Time3 as usual
8
Indexers• Allow usage of objects using array notation.• Borrowed from C++ ability to overload the [] operator
(not possible in C#, or in Java).• Allows using objects, like this:
• obj[0], … to mean obj.getX(), if index 0 refers to instance variable x.
• obj[0] = 7 to mean obj.setX(7).
• The indexes 0, 1, 2, … refer to instance variables of the class of object obj. Index 0 refers to first instance variable, index 1 refers to second instance variable, etc.
10
Usage of indexer of Weight
this[0] returns the value of lb. ( and, likewise, w[0] would also refer to lb of w, where w is an
object of type Weight.)
11
Indexer to refer to instance var someArray. (index 0 refers to someArray[0], 1 refers to someArray[1], etc)
21
Passing Arguments to methods: C# supports both Call-By-Value and pass and Call-By-Reference
• Passing by value (same as Java)– Send a method a copy of the object– When returned are always returned by value– Set by value by default
• Passing by reference (same as passing a pointer in C, C++)– Send a method the actual reference point
• Causes the variable to be changed throughout the program– When returned are always returned by reference– The ref keyword specifies by reference– The out keyword means a called method will initialize it
22
RefOutTest.cs1 // RefOutTest.cs2 // Demonstrating ref and out parameters.34 using System;5 using System.Windows.Forms;67 class RefOutTest8 {9 // x is passed as a ref int (original value will change)10 static void SquareRef( ref int x )11 {12 x = x * x;13 }1415 // original value can be changed and initialized16 static void SquareOut( out int x )17 {18 x = 6;19 x = x * x;20 }2122 // x is passed by value (original value not changed)23 static void Square( int x )24 {25 x = x * x;26 }2728 static void Main( string[] args )29 {30 // create a new integer value, set it to 531 int y = 5;32 int z; // declare z, but do not initialize it33
23
RefOutTest.cs34 // display original values of y and z35 string output1 = "The value of y begins as "36 + y + ", z begins uninitialized.\n\n\n";3738 // values of y and z are passed by value39 RefOutTest.SquareRef( ref y );40 RefOutTest.SquareOut( out z );41 42 // display values of y and z after modified by methods43 // SquareRef and SquareOut44 string output2 = "After calling SquareRef with y as an " +45 "argument and SquareOut with z as an argument,\n" +46 "the values of y and z are:\n\n" + 47 "y: " + y + "\nz: " + z + "\n\n\n";48 49 // values of y and z are passed by value50 RefOutTest.Square( y );51 RefOutTest.Square( z );5253 // values of y and z will be same as before because Square54 // did not modify variables directly55 string output3 = "After calling Square on both x and y, " +56 "the values of y and z are:\n\n" +57 "y: " + y + "\nz: " + z + "\n\n";58 59 MessageBox.Show( output1 + output2 + output3, 60 "Using ref and out Parameters", MessageBoxButtons.OK,61 MessageBoxIcon.Information );62 63 } // end method Main64 65 } // end class RefOutTest
passed by reference
passed by value
25
const and readonly Members• Declare constant members (members
whose value will never change) using the keyword const (equivalent to java’s final)
• const members are implicitly static• const members must be initialized when
they are declared• Use keyword readonly to declare
members who will be initialized in the constructor but not change after that
26
UsingConstAndReadOnly.cs
1 // UsingConstAndReadOnly.cs2 // Demonstrating constant values with const and readonly.3 4 using System;5 7 // Constants class definition8 public class Constants9 {10 // PI is constant variable11 public const double PI = 3.14159;12 13 // radius is a constant variable14 // that is uninitialized15 public readonly int radius;16 17 public Constants( int radiusValue )18 {19 radius = radiusValue;20 }22 } // end class Constants
Constant variable PI
Readonly variable radius; must be initialized in constructor
Initialize readonlymember radius
27
UsingConstAndReadOnly.cs
1 // UsingConstAndReadOnly.cs2 // Demonstrating constant values with const and
readonly.3 4 24 // UsingConstAndReadOnly class definition25 public class UsingConstAndReadOnly26 {27 // method Main creates Constants 28 // object29 static void Main( string[] args )30 { 31 Random random = new Random();32 33 Constants constantValues = 34 new Constants( random.Next( 1, 20 ) );35
28
UsingConstAndReadOnly.cs36 MessageBox.Show( "Radius = " +
constantValues.radius + 37 "\nCircumference = " + 38 2 * Constants.PI * constantValues.radius,39 "Circumference" );40 41 } // end method Main42 43 } // end class UsingConstAndReadOnly
Output from two separate runs
30
1 // SumArray.cs2 // Computing the sum of the elements in an array.3 4 using System;5 using System.Windows.Forms;6 7 class SumArray8 {9 // main entry point for application10 static void Main( string[] args )11 {12 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };13 int total = 0;14 15 for ( int i = 0; i < a.Length; i++ )16 total += a[ i ];17 18 MessageBox.Show( "Total of array elements: " + total,19 "Sum the elements of an array",20 MessageBoxButtons.OK, MessageBoxIcon.Information );21 22 } // end Main23 24 } // end class SumArray
Declare integer array a and initialize it
Total the contents of array a
31
Passing Arrays to Methods
• Pass arrays as arguments to methods by specifying the name of the array (no brackets)
• Arrays are passed by reference• Individual array elements are passed by value
32
PassArray.cs1 // Fig. 7.8: PassArray.cs2 // Passing arrays and individual elements to methods.3 using System;4 using System.Drawing;5 using System.Collections;6 using System.ComponentModel;7 using System.Windows.Forms;8 using System.Data;9 10 public class PassArray : System.Windows.Forms.Form11 {12 private System.Windows.Forms.Button showOutputButton;13 private System.Windows.Forms.Label outputLabel;14 15 // Visual Studio .NET generated code16 17 [STAThread]18 static void Main() 19 {20 Application.Run( new PassArray() );21 }22 23 private void showOutputButton_Click( object sender, 24 System.EventArgs e )25 {26 int[] a = { 1, 2, 3, 4, 5 };27 28 outputLabel.Text = "Effects of passing entire array " +29 "call-by-reference:\n\nThe values of the original " +30 "array are:\n\t";31 32 for ( int i = 0; i < a.Length; i++ )33 outputLabel.Text += " " + a[ i ];34 35 ModifyArray( a ); // array is passed by reference
Declare and initialize integer array a
Output contents of array a
Call method ModifyArray, pass array a as an argument by reference
33
PassArray.cs36 37 outputLabel.Text += 38 "\n\nThe values of the modified array are:\n\t";39 40 // display elements of array a41 for ( int i = 0; i < a.Length; i++ )42 outputLabel.Text += " " + a[ i ];43 44 outputLabel.Text += "\n\nEffects of passing array " +45 "element call-by-value:\n\na[ 3 ] before " +46 "ModifyElement: " + a[ 3 ];47 48 // array element passed call-by-value49 ModifyElement( a[ 3 ] );50 51 outputLabel.Text += 52 "\na[ 3 ] after ModifyElement: " + a[ 3 ];53 }54 55 // method modifies the array it receives,56 // original will be modified57 public void ModifyArray( int[] b )58 {59 for ( int j = 0; j < b.Length; j++ )60 b[ j ] *= 2;61 }62 63 // method modifies the integer passed to it64 // original will not be modified65 public void ModifyElement( int e )66 {67 outputLabel.Text += 68 "\nvalue received in ModifyElement: " + e;69
Output array a after ModifyArraychanged the contents
Call method ModifyElement, pass element of array a that is at index 3
Replace every element in array by twice its value
34
PassArray.cs70 e *= 2;71 72 outputLabel.Text += 73 "\nvalue calculated in ModifyElement: " + e;74 }75 }
Multiply argument by two
This does not change value of element in original array, because the element was passed by value
35
Passing Arrays by Value and by Reference
• Variables that “store” object, actually store references to those objects
• A reference is a location in computer’s memory where the object itself is stored
• Passing value types to methods– A copy of the variable is made– Any changes to variable in method do not effect the original variable
• Passing reference types to methods– A copy of the reference to the object is made– Any changes to the reference in the method do not effect the
original variable– Any changes to the contents of the object in the method, do effect
the object outside the method
36
Passing Arrays by Value and by Reference
• Keyword ref may be used to pass arguments to method by reference– Value type variables are not copied – modifying the variable in
the method will modify the variable outside the method– References to objects are not copied – modifying the reference
in the method will modify the reference outside the method
• Programmers have to be careful when using ref– May lead to references being set to null– May lead to methods modifying variable values and references
in ways that are not desired
37
ArrayReferenceTest.cs1 // ArrayReferenceTest.cs2 // Testing the effects of passing array references3 // by value and by reference.4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;10 11 public class ArrayReferenceTest : System.Windows.Forms.Form12 {13 private System.Windows.Forms.Label outputLabel;14 private System.Windows.Forms.Button showOutputButton;15 16 [STAThread]17 static void Main() 18 {19 Application.Run( new ArrayReferenceTest() );20 }21 22 private void showOutputButton_Click( object sender, 23 System.EventArgs e )24 {25 // create and initialize firstArray26 int[] firstArray = { 1, 2, 3 };27 28 // copy firstArray reference29 int[] firstArrayCopy = firstArray;30 31 outputLabel.Text += 32 "Test passing firstArray reference by value";33 34 outputLabel.Text += "\n\nContents of firstArray " +35 "before calling FirstDouble:\n\t";
Declare and initialize integer array firstArray
Declare integer array firstArrayCopy and have it reference firstArray
38
ArrayReferenceTest.cs36 37 // print contents of firstArray38 for ( int i = 0; i < firstArray.Length; i++ )39 outputLabel.Text += firstArray[ i ] + " ";40 41 // pass reference firstArray by value to FirstDouble42 FirstDouble( firstArray );43 44 outputLabel.Text += "\n\nContents of firstArray after " +45 "calling FirstDouble\n\t";46 47 // print contents of firstArray48 for ( int i = 0; i < firstArray.Length; i++ )49 outputLabel.Text += firstArray[ i ] + " ";50 51 // test whether reference was changed by FirstDouble52 if ( firstArray == firstArrayCopy )53 outputLabel.Text += 54 "\n\nThe references refer to the same array\n";55 else56 outputLabel.Text += 57 "\n\nThe references refer to different arrays\n";58 59 // create and initialize secondArray60 int[] secondArray = { 1, 2, 3 };61 62 // copy secondArray reference63 int[] secondArrayCopy = secondArray;64 65 outputLabel.Text += "\nTest passing secondArray " +66 "reference by reference";67 68 outputLabel.Text += "\n\nContents of secondArray " +69 "before calling SecondDouble:\n\t";70
Output contents of firstArray
Call method FirstDoubleon firstArray
Output contents of firstArray
Test whether firstArray and firstArrayCopyreference the same object
Declare and initialize integer array secondArray
Declare integer array secondArrayCopy and set it to reference secondArray
39
ArrayReferenceTest.cs71 // print contents of secondArray before method call72 for ( int i = 0; i < secondArray.Length; i++ )73 outputLabel.Text += secondArray[ i ] + " ";74 75 SecondDouble( ref secondArray );76 77 outputLabel.Text += "\n\nContents of secondArray " +78 "after calling SecondDouble:\n\t";79 80 // print contents of secondArray after method call81 for ( int i = 0; i < secondArray.Length; i++ )82 outputLabel.Text += secondArray[ i ] + " ";83 84 // test whether reference was changed by SecondDouble85 if ( secondArray == secondArrayCopy )86 outputLabel.Text += 87 "\n\nThe references refer to the same array\n";88 else89 outputLabel.Text += 90 "\n\nThe references refer to different arrays\n"; 91 92 } // end method showOutputButton_Click93 94 // modify elements of array and attempt to modify95 // reference 96 void FirstDouble( int[] array )97 {98 // double each element's value99 for ( int i = 0; i < array.Length; i++ )100 array[ i ] *= 2;101 102 // create new reference and assign it to array103 array = new int[] { 11, 12, 13 };104 }105
Output contents of secondArray
Call method SecondDoubleand pass secondArray by reference
Output contents of secondArray
Test whether secondArrayand secondArrayCopyreference the same object
Replace each element in the array by twice its value
Set array to reference a new integer array containing the values 11, 12 and 13
40
ArrayReferenceTest.cs
Program Output
106 // modify elements of array and change reference array107 // to refer to a new array108 void SecondDouble( ref int[] array )109 {110 // double each element's value111 for ( int i = 0; i < array.Length; i++ )112 array[ i ] *= 2;113 114 // create new reference and assign it to array115 array = new int[] { 11, 12, 13 };116 } 117 }
Replace each element in the array by twice its valueSet array to reference a new integer array
containing the values 11, 12 and 13
41
foreach Repetition Structure
• The foreach repetition structure is used to iterate through values in data structures such as arrays
• No counter• A variable is used to represent the value of each element
42
ForEach.cs1 // ForEach.cs2 // Demonstrating for/each structure.3 using System;4 5 class ForEach6 {7 // main entry point for the application8 static void Main( string[] args )9 {10 int[,] gradeArray = { { 77, 68, 86, 73 }, 11 { 98, 87, 89, 81 }, { 70, 90, 86, 81 } };12 13 int lowGrade = 100;14 15 foreach ( int grade in gradeArray )16 {17 if ( grade < lowGrade )18 lowGrade = grade;19 }20 21 Console.WriteLine( "The minimum grade is: " + lowGrade );22 }23 }
The minimum grade is: 68
Use the foreach loop to examine each element in the array
If the current array element is smaller than lowGrade, set lowGradeto contain the value of the current element
44
Point3.cs1 // Point3.cs2 // Point3 class represents an x-y coordinate pair.4 using System;6 // Point3 class definition implicitly inherits from Object7 public class Point38 {9 // point coordinate10 private int x, y;12 // default constructor13 public Point3()14 {15 // implicit call to Object constructor occurs here16 }17 18 // constructor19 public Point3( int xValue, int yValue )20 {21 // implicit call to Object constructor occurs here22 X = xValue; // use property X23 Y = yValue; // use property Y24 }25 26 // property X27 public int X28 {29 get30 {31 return x;32 }33
Declare coordinates as private
45
Point3.cs34 set35 {36 x = value; // no need for validation37 }38 39 } // end property X40 41 // property Y42 public int Y43 {44 get45 {46 return y;47 }48 49 set50 {51 y = value; // no need for validation52 }53 54 } // end property Y55 56 // return string representation of Point357 public override string ToString()58 {59 return "[" + X + ", " + Y + "]";60 }61 62 } // end class Point3
Methods to set x and y coordinates
Overridden ToString method
46
Circle4.cs1 // Circle4.cs2 // Circle4 class that inherits from class Point3.4 using System;6 // Circle4 class definition inherits from Point37 public class Circle4 : Point38 {9 private double radius;10 11 // default constructor12 public Circle4()13 {14 // implicit call to Point constructor occurs here15 }17 // constructor18 public Circle4( int xValue, int yValue, double radiusValue )19 : base( xValue, yValue )20 {21 Radius = radiusValue;22 }24 // property Radius25 public double Radius26 {27 get28 {29 return radius;30 }32 set33 {34 if ( value >= 0 ) // validation needed35 radius = value;
Constructor with explicit call to base class constructor
Explicit call to base class constructor
Constructor with implicit call to base class constructor
47
Circle4.cs36 }38 } // end property Radius39 40 // calculate Circle diameter41 public double Diameter()42 {43 return Radius * 2; // use property Radius44 }45 46 // calculate Circle circumference47 public double Circumference()48 {49 return Math.PI * Diameter();50 }51 52 // calculate Circle area53 public virtual double Area()54 {55 return Math.PI * Math.Pow( Radius, 2 ); // use property56 }57 58 // return string representation of Circle459 public override string ToString()60 {61 // use base reference to return Point string representation62 return "Center= " + base.ToString() +63 "; Radius = " + Radius; // use property Radius64 }66 } // end class Circle4
Circle4’s ToString method overrides Point3’s ToStringmethod
Call Point3’s ToStringmethod to display coordinates
Method area declared virtual so it can be overridden
48
CircleTest4.cs1 // CircleTest4.cs2 // Testing class Circle4.4 using System;5 using System.Windows.Forms;7 // CircleTest4 class definition8 class CircleTest49 {10 // main entry point for application11 static void Main( string[] args )12 {13 // instantiate Circle414 Circle4 circle = new Circle4( 37, 43, 2.5 );15 16 // get Circle4's initial x-y coordinates and radius17 string output = "X coordinate is " + circle.X + "\n" +18 "Y coordinate is " + circle.Y + "\n" + 19 "Radius is " + circle.Radius;21 // set Circle4's x-y coordinates and radius to new values22 circle.X = 2;23 circle.Y = 2;24 circle.Radius = 4.25;26 // display Circle4's string representation27 output += "\n\n" +28 "The new location and radius of circle are " +29 "\n" + circle + "\n";30 31 // display Circle4's Diameter32 output += "Diameter is " + 33 String.Format( "{0:F}", circle.Diameter() ) + "\n";34
Create new Circle4 object
Change coordinates and radius of Circle4 object
Implicit call to Circle4’s ToString method
49
CircleTest4.cs35 // display Circle4's Circumference36 output += "Circumference is " +37 String.Format( "{0:F}", circle.Circumference() ) + "\n";38 39 // display Circle4's Area40 output += "Area is " + 41 String.Format( "{0:F}", circle.Area() );42 43 MessageBox.Show( output, "Demonstrating Class Circle4");44 45 } // end method Main46 47 } // end class CircleTest4
Call Circle’s Circumference and Area methods for output
50
sealed Classes and Methods
• sealed is a keyword in C# (equivalent to final in Java)• sealed methods cannot be overridden in a derived class
– Methods that are declared static and private, are implicitly sealed
• sealed classes cannot have any derived-classes• Creating sealed classes can allow some runtime
optimizations– e.g., virtual method calls can be transformed into non-virtual
method calls
51
Building Graphical User Interfaces
• Graphical user interface– Allow interaction with program visually– Give program distinct look and feel– Built from window gadgets – Is an object, accessed via keyboard or mouse
58
Select any component from toolbox …
The GUI components available in C#. Select and drag into the design Form …
59
Drag the component inside the Form (or click in the Form after having clicked on the component)
A Button has been selected from the
Toolbox and placed into the Form
60
Inside the Form … select the button and right-click … get properties menu
Use these to adjust the properties of the
component (e.g., font used, background color,
etc).
62
Generating the event code …
Double click on “Click” and VS will generate the event code….
Click is one of the
available Events for
Button.
63
The generated event related code …
Programmer fills in this part …
All this code has been generated by
VS.NET
64
IntroductionControl Description Label An area in which icons or uneditable text can be displayed.
TextBox An area in which the user inputs data from the keyboard. The area also can display information.
Button An area that triggers an event when clicked. CheckBox A GUI control that is either selected or not selected. ComboBox A drop-down list of items from which the user can make a selection,
by clicking an item in the list or by typing into the box, if permitted. ListBox An area in which a list of items is displayed from which the user can
make a selection by clicking once on any element. Multiple elements can be selected.
Panel A container in which components can be placed. ScrollBar Allows the user to access a range of values that cannot normally fit in
its container.
Some basic GUI components.
65
Windows Forms
• WinForms– Create GUIs for programs– Element on the desktop– Represented by:
• Dialog• Window• MDI window
66
Basic Event Handling
Events section of the Properties window.
Current even handler (none)
Selected event
Event description
List of events supported by control
Events icon
67
SimpleEventExample.cs1 // SimpleEventExample.cs2 // Using Visual Studio .NET to create event handlers.4 using System;5 using System.Drawing;6 using System.Collections;7 using System.ComponentModel;8 using System.Windows.Forms;9 using System.Data;11 // program that shows a simple event handler12 public class MyForm : System.Windows.Forms.Form13 {14 private System.ComponentModel.Container components = null;15 16 // Visual Studio .NET generated code18 [STAThread]19 static void Main() 20 {21 Application.Run( new MyForm() );22 }24 // Visual Studio .NET creates an empty handler, 25 // we write definition: show message box when form clicked
26 private void MyForm_Click( object sender, System.EventArgs e )
27 {
28 MessageBox.Show( "Form was pressed" );
29 }
30 31 } // end class MyForm
68
Labels, TextBoxes and Buttons• Labels
– Provide text instruction• Read only text
– Defined with class Label• Derived from class Control
• Textbox– Class TextBox– Area for text input
• Password textbox• Button
– Control to trigger a specific action• Checkboxes or radio buttons
– Derived from ButtonBase
69
Labels TextBoxes and Buttons
Label Properties
Description / Delegate and Event Arguments
Common Properties
Font The font used by the text on the Label. Text The text to appear on the Label. TextAlign The alignment of the Label’s text on the control. One of three horizontal positions
(left, center or right) and one of three vertical positions (top, middle or bottom).
Label properties.
70
Labels TextBoxes and ButtonsTextBox Properties and Events
Description / Delegate and Event Arguments
Common Properties
AcceptsReturn If true, pressing Enter creates a new line if textbox spans multiple lines. If false, pressing Enter clicks the default button of the form.
Multiline If true, textbox can span multiple lines. Default is false. PasswordChar Single character to display instead of typed text, making the
TextBox a password box. If no character is specified, Textbox displays the typed text.
ReadOnly If true, TextBox has a gray background and its text cannot be edited. Default is false.
ScrollBars For multiline textboxes, indicates which scrollbars appear (none, horizontal, vertical or both).
Text The text to be displayed in the text box. Common Events (Delegate EventHandler, event arguments EventArgs) TextChanged Raised when text changes in TextBox (the user added or deleted
characters). Default event when this control is double clicked in the designer.
TextBox properties and events.
71
Labels TextBoxes and Buttons
Button properties and events
Description / Delegate and Event Arguments
Common Properties Text Text displayed on the Button face. Common Events (Delegate EventHandler, event arguments EventArgs) Click Raised when user clicks the control. Default event when this control is
double clicked in the designer.
Button properties and events.
74
The code …• using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;
• namespace WindowsApplication3_2• {• /// <summary>• /// Summary description for Form1.• /// </summary>• public class Form1 : System.Windows.Forms.Form• {
• private System.Windows.Forms.TextBox textBox1;• private System.Windows.Forms.Label label1;• private System.Windows.Forms.Button button1;• /// <summary>• /// Required designer variable.• /// </summary>• private System.ComponentModel.Container components = null;
• public Form1()• {• //• // Required for Windows Form Designer support• //• InitializeComponent();
• //• // TODO: Add any constructor code after InitializeComponent call• //• }
Declared components
75
…• private void InitializeComponent()• {• this.textBox1 = new
System.Windows.Forms.TextBox();• this.label1 = new System.Windows.Forms.Label();• this.button1 = new
System.Windows.Forms.Button();• this.SuspendLayout();• // • // textBox1• // • this.textBox1.Location = new
System.Drawing.Point(32, 48);• this.textBox1.Name = "textBox1";• this.textBox1.PasswordChar = '*';• this.textBox1.Size = new
System.Drawing.Size(176, 20);• this.textBox1.TabIndex = 0;• this.textBox1.Text = "";• this.textBox1.TextChanged += new
System.EventHandler(this.textBox1_TextChanged);• // • // label1• // • this.label1.BackColor =
System.Drawing.SystemColors.Info;• this.label1.Location = new
System.Drawing.Point(32, 96);• this.label1.Name = "label1";• this.label1.Size = new System.Drawing.Size(176,
23);• this.label1.TabIndex = 1;
Construct components
Event handler for textBox, but never used. (added automatically by vs .net)
Set property so that chars appear as ‘*’ when typed in
textBox1.
76
…• // • // button1• // • this.button1.Location = new System.Drawing.Point(48,
144);• this.button1.Name = "button1";• this.button1.Size = new System.Drawing.Size(152, 23);• this.button1.TabIndex = 2;• this.button1.Text = "Show password";• this.button1.Click += new
System.EventHandler(this.button1_Click);• // • // Form1• // • this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);• this.ClientSize = new System.Drawing.Size(292, 273);• this.Controls.AddRange(new System.Windows.Forms.Control[]
{•
this.button1,•
this.label1,•
this.textBox1});• this.Name = "Form1";• this.Text = "Form1";• this.ResumeLayout(false);
• }• #endregion
Event handler for button. (generated by vs.net, and implemented by programmer).
77
…• /// <summary>• /// Clean up any resources being used.• /// </summary>• protected override void Dispose( bool disposing )• {• if( disposing )• {• if (components != null) • {• components.Dispose();• }• }• base.Dispose( disposing );• }
• private void button1_Click(object sender, System.EventArgs e)• {• label1.Text = textBox1.Text;• }
• private void textBox1_TextChanged(object sender, System.EventArgs e)
• {•• }
• #region Windows Form Designer generated code• /// <summary>• /// Required method for Designer support - do not modify• /// the contents of this method with the code editor.• /// </summary>• /// <summary>
This line added by programmer.
78
…
• /// The main entry point for the application.
• /// </summary>
• [STAThread]
• static void Main()
• {
• Application.Run(new Form1());
• }
• }
• }
79
GroupBoxes and Panels
• Arrange components on a GUI– GroupBoxes can display a caption
• Text property determines its caption– Panels can have scrollbar
• View additional controls inside the Panel
80
GroupBoxes and Panels
GroupBox Properties Description Common Properties
Controls The controls that the GroupBox contains. Text Text displayed on the top portion of the GroupBox (its caption).
GroupBox properties.
81
GroupBoxes and Panels
Panel Properties Description Common Properties
AutoScroll Whether scrollbars appear when the Panel is too small to hold its controls. Default is false.
BorderStyle Border of the Panel (default None; other options are Fixed3D and FixedSingle).
Controls The controls that the Panel contains.
Panel properties.
83
The code• using System;• using System.Drawing;• using System.Collections;• using System.ComponentModel;• using System.Windows.Forms;• using System.Data;• namespace WindowsApplication3_3• {• /// <summary>• /// Summary description for Form1.• /// </summary>• public class Form1 : System.Windows.Forms.Form• {• private System.Windows.Forms.GroupBox groupBox1;• private System.Windows.Forms.Button button1;• private System.Windows.Forms.Button button2;• private System.Windows.Forms.Panel panel1;• private System.Windows.Forms.Button button3;• private System.Windows.Forms.Button button4;• private System.Windows.Forms.Label label1;• /// <summary>• private System.ComponentModel.Container components = null;
• public Form1()• {• //• // Required for Windows Form Designer support• //• InitializeComponent();
• //• // TODO: Add any constructor code after InitializeComponent call• //• }
Declared components
84
…• //….. • private void InitializeComponent()• {• this.groupBox1 = new System.Windows.Forms.GroupBox();• this.button1 = new System.Windows.Forms.Button();• this.button2 = new System.Windows.Forms.Button();• this.panel1 = new System.Windows.Forms.Panel();• this.button3 = new System.Windows.Forms.Button();• this.button4 = new System.Windows.Forms.Button();• this.label1 = new System.Windows.Forms.Label();• this.groupBox1.SuspendLayout();• this.panel1.SuspendLayout();• this.SuspendLayout();• // • // groupBox1• // • this.groupBox1.BackColor = System.Drawing.SystemColors.Desktop;• this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {•
this.button2,•
this.button1});• this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.groupBox1.Location = new System.Drawing.Point(40, 32);• this.groupBox1.Name = "groupBox1";• this.groupBox1.Size = new System.Drawing.Size(240, 96);• this.groupBox1.TabIndex = 0;• this.groupBox1.TabStop = false;• this.groupBox1.Text = "GroupBox with 2 buttons";• // • // button1• // • this.button1.BackColor = System.Drawing.Color.Red;• this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.button1.Location = new System.Drawing.Point(16, 40);• this.button1.Name = "button1";• this.button1.Size = new System.Drawing.Size(80, 32);• this.button1.TabIndex = 0;• this.button1.Text = "button1";
• this.button1.Click += new System.EventHandler(this.button1_Click);
Configure components.
Construct components
Hookup to events
85
…• // • // button2• // • this.button2.BackColor = System.Drawing.Color.Red;• this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.button2.Location = new System.Drawing.Point(144, 32);• this.button2.Name = "button2";• this.button2.Size = new System.Drawing.Size(80, 32);• this.button2.TabIndex = 1;• this.button2.Text = "exit";
• this.button2.Click += new System.EventHandler(this.button2_Click);• //
• // panel1• // • this.panel1.BackColor = System.Drawing.SystemColors.Desktop;• this.panel1.Controls.AddRange(new System.Windows.Forms.Control[] {•
this.button4,•
this.button3});• this.panel1.Location = new System.Drawing.Point(40, 184);• this.panel1.Name = "panel1";• this.panel1.Size = new System.Drawing.Size(224, 96);• this.panel1.TabIndex = 1;
• this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
• // • // button3• // • this.button3.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),
((System.Byte)(0)), ((System.Byte)(192)));• this.button3.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.button3.ForeColor = System.Drawing.SystemColors.ControlLightLight;• this.button3.Location = new System.Drawing.Point(16, 48);• this.button3.Name = "button3";• this.button3.Size = new System.Drawing.Size(80, 32);• this.button3.TabIndex = 0;• this.button3.Text = "button3";
• this.button3.Click += new System.EventHandler(this.button3_Click);•
86
….• // • // button4• // • this.button4.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),
((System.Byte)(0)), ((System.Byte)(192)));• this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.button4.ForeColor = System.Drawing.SystemColors.ControlLightLight;• this.button4.Location = new System.Drawing.Point(136, 48);• this.button4.Name = "button4";• this.button4.Size = new System.Drawing.Size(80, 32);• this.button4.TabIndex = 1;• this.button4.Text = "button4";
• this.button4.Click += new System.EventHandler(this.button4_Click);• //
• // label1• // • this.label1.BackColor = System.Drawing.Color.Yellow;• this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F,
(System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic), System.Drawing.GraphicsUnit.Point, ((System.Byte)(161)));• this.label1.Location = new System.Drawing.Point(64, 144);• this.label1.Name = "label1";• this.label1.Size = new System.Drawing.Size(168, 23);• this.label1.TabIndex = 2;• this.label1.Text = "no button pressed";• this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;• // • // Form1• // • this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);• this.ClientSize = new System.Drawing.Size(296, 317);• this.Controls.AddRange(new System.Windows.Forms.Control[] {•
this.label1,•
this.panel1,•
this.groupBox1});• this.Name = "Form1";• this.Text = "Form1";• this.groupBox1.ResumeLayout(false);• this.panel1.ResumeLayout(false);• this.ResumeLayout(false);
• }• #endregion
87
….• /// <summary>• /// The main entry point for the application.• /// </summary>• [STAThread]• static void Main() • {• Application.Run(new Form1());• }
• private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
• {•• }
• private void button1_Click(object sender, System.EventArgs e)• {• label1.Text = "Button 1 pressed";• }
• private void button2_Click(object sender, System.EventArgs e)• {• this.Close();• }
• private void button3_Click(object sender, System.EventArgs e)• {• label1.Text = "Button 3 pressed";• }
• private void button4_Click(object sender, System.EventArgs e)• {• label1.Text = "Button 4 pressed";• }• }• }
Event handling code for the four
buttons.
Event handling for rendering the panel (automatically generated).