Download presentation
Presentation is loading. Please wait.
1
Visual programming Using C#
Chapter three Flow-of-Control Statements Prof. Yousef B. Mahdy
2
Specifying Operator Precedence
An expression can contain a complex series of operators and operands. The order in which the operators are processed and the operands are evaluated depends on the operators themselves. In many cases, there is not always a simple left-to-right flow of an expression. The operators that you use to build an expression each have an associated precedence that determines the order in which they are processed. Also, operators have a particular associativity, which determines the order in which they are processed in relation to operators with a matching precedence. To make expressions work in exactly the way you want them to, you can control processing order by using parentheses.
3
1
4
Operator Associativity
When you use operators of the same precedence, the operator associativity is used to determine the order of processing. Operators are either right-associative or leftassociative. Left-associative operators are processed from left to right, for example, the / operator, as the following code example shows. a / 5 / b Here, a is divided by 5 and then the result of that division is divided by b. All binary operators are left-associative apart from assignment operators, which are right-associative, as the following code example shows.
5
1
6
Flow-of-Control Statements
By default, C# performs the statements in a program in a sequential manner. However, you frequently need to specify that alternative statements should run depending on the value of an expression or a Boolean condition. To achieve this, C# provides the flow-of-control constructs common to modern programming languages. Conditional execution executes or skips a section of code depending on a condition. The conditional execution statements are the following: – if – if...else – switch Looping statements repeatedly execute a section of code. The looping statements are the following: – while – do – for – foreach
7
1 Jump statements change the flow of control from one section of code to a specific statement in another section of code. The jump statements are the following: – break – continue – return – goto – throw Conditional execution and looping constructs (other than foreach) require a test expression, or condition, to determine where the program should continue execution. Unlike C and C++, test expressions must return a value of type bool. Numbers do not have a Boolean interpretation in C#.
8
Using One-Way If Statements
9
1 The if statement implements conditional execution. The syntax for the if statement is shown here, and is illustrated:
10
Example
11
The if else Statement The if...else statement implements a two-way branch. The syntax for the if...else statement is shown here, and is illustrated :
12
Example
13
Using the ?: Operator As an alternative to using the if else statements, in some simple cases, you can use the ?: ternary operator. The basic syntax to use the ?: operator is shown in the following code example. Type result = [condition] ? [true expression] : [false expression] In this code, if the expression [condition] evaluates to true, [true expression] is executed, but if the [condition] evaluates to false, [false expression] is executed. The following code example shows an example of using the ?: operator to check the value of a string, and then return a response.
14
Using Multiple-Outcome If Statements
You can combine several if statements to create a multiple-outcome statement. The following code example shows an example of the syntax.
15
1 It is important to note that if [condition] is true, the first block of code is executed, regardless of the value of [condition2]. If this is the case, the remaining code is skipped, and [condition2] is not evaluated. This has performance consequences because it takes time for each condition to be evaluated. You can streamline your code by ensuring that the most commonly fulfilled condition or the condition that takes least processing to evaluate is tested first. The following code example shows an example of a multiple-outcome statement that uses this structure.
16
Example
17
The switch Statement The basic syntax for the switch statement is shown in the following code example.
18
1 In a switch statement, you specify the expression to check in [expression to check], and supply values to compare with the variable in [testX]. Each comparison is tested in turn, so if [expression to check] equals [test1], the first code block is executed, if [expression to check] equals [test2], the second code block is executed, and so on. There is no limit to the number of comparisons that you can include here, other than the memory of your computer. If no match is made, the block of code that is specified by default: is executed. The default block is optional. The type of value that [expression to check] returns must be an integer, string, or Boolean, and the values that are specified by the case statements must match this type.
19
2
20
3 Each comparison ([testX]) is a single value. You can also check for multiple values by using multiple consecutive case statements, as the following code example shows.
21
4 Every block of code in a switch statement must end with a statement that explicitly terminates the construct (shown as [exit case statement] in the earlier example). If you omit this statement, your code will not compile. You can use the following statements: Break: This statement terminates processing of the selection statement. goto case [testX]:This statement causes execution to jump to the specified block of code in the switch statement. Return: This statement causes the switch statement and its containing method to terminate. You can pass return values with this statement.
22
A Switch Example
23
Example
24
5 Although C# does not allow falling through from one switch section to another: You can attach multiple switch labels to any switch section. Following the statement list associated with a case, there must be a break or goto statement before the next switch label, unless there are no intervening executable statements between the switch labels. For example, in the following code, since there are no executable statements between the first three switch labels, it’s fine to have one follow the other. Cases 5 and 6, however, have an executable statement between them, so there must be a break or goto statement before case 6.
25
6
26
Using Iteration Statements
When you are writing the logic for your .NET Framework applications, it is common for you to want to repeatedly execute a section of logic either a set amount of times, or until a condition is met. To achieve this, you can use the iteration statements that C# provides. This part introduces the three main iteration statements that are available in C# and explains how you can use them in your applications.
27
Types of Iteration Statements
28
While Loops A while loop enables you to execute a block of code zero or more times. While loops do not use a counter variable, although you can implement a counter variable by defining it outside the loop and manipulating it for each iteration. At the start of each iteration of a while loop, a Boolean condition is checked. If this condition evaluates to true, an iteration begins. If the condition evaluates to false, the loop terminates. While loops can be very useful if you do not know in advance whether you must perform iterative processing on a variable.
29
Do loops Do loops are exactly like while loops apart from one detail. In a do loop, the condition is evaluated at the end of the iteration instead of at the start. This means that a do loop always executes at least once, unlike a while loop, which might not execute at all. Do loops are very useful when you do not know in advance how many times your code needs to execute. For example, you can use a do loop to prompt a user repeatedly until the user provides valid input.
30
For Loops A for loop enables you to execute code repeatedly a set number of times. To achieve this, you define a counter variable for the loop, the value of which is changed for each iteration. When the counter variable reaches a limit value that you define, the loop terminates. The code in the body of a for loop can use the value of the counter variable. This means, for example, that you can use a for loop to process each member of an array. You can also nest for loops with different counters so that you can process multidimensional arrays or examine pixels at specified coordinates.
31
Using the While Statement
The while loop is a simple loop construct in which the test expression is performed at the top of the loop. The syntax of the while loop is shown here, and is illustrated:
32
Example
33
The do Loop The do loop is a simple loop construct in which the test expression is performed at the bottom of the loop. The syntax for the do loop is shown here and illustrated: condition statement false true
34
1
35
2
36
Nested Loops
37
The for loop The for loop construct executes the body of the loop as long as the test expression returns true when it is evaluated at the top of the loop. The syntax of the for loop is shown here and illustrated:
38
3
39
4 Initializer, TestExpr, and IterationExpr are all optional. Their positions can be left blank. If the TestExpr position is left blank, the test is assumed to return true. Therefore, there must be some other method of exiting the statement if the program is to avoid going into an infinite loop. The semicolons are required.
40
Example
41
The Scope of Variables in a for Statement
42
Multiple Expressions in the Initializer and Iteration Expression
43
Keywords break and continue
The syntax of the while and do..while loops allows you to test the continuation condition at either the beginning of a loop or at the end. Sometimes, it is more natural to have the test in the middle of the loop, or to have several tests at different places in the same loop. Java provides a general method for breaking out of the middle of any loop. It's called the break statement, which takes the form: break; When the computer executes a break statement in a loop, it will immediately jump out of the loop. It then continues on to whatever follows the loop in the program. Consider for example:
44
Example
45
Example The following program is a variant of the one that outputs numbers between 1 and 10, with the first and third expressions inside the parentheses being empty because num is initialized before the for loop and incremented inside the body of the loop. private void Form1_Load(object sender, EventArgs e){ int num = 1; for (;;) { if (num > 10) break; else { MessageBox.Show(num + " "); num++; }
46
Example while (true) { // looks like it will run forever!
Console.WriteLine("Enter a positive number: "); int N=Int32.Parse(Console.ReadLine()); if (N > 0) // input is OK; jump out of loop break; Console.WriteLine("Your answer must be > 0."); } // continue here after break If the number entered by the user is greater than zero, the break statement will be executed and the computer will jump out of the loop. Otherwise, the computer will print out "Your answer must be > 0." and will jump back to the start of the loop to read another input value.
47
The Continue Keyword The continue keyword, like the break keyword, is used within the code of a for statement, commonly within an if/else structure. If the continue statement is reached, the current iteration of the loop ends, and the next iteration of the loop begins. A continue statement tells the computer to skip the rest of the current iteration of the loop. However, instead of jumping out of the loop altogether, it jumps back to the beginning of the loop and continues with the next iteration (including evaluating the loop's continuation condition to see whether any further iterations are required).
48
Example
49
Example private void btnTest_Click(object sender, EventArgs e){
string strItems; int intItems, total = 0; strItems = txtInput.Text; intItems = Int32.Parse(strItems); for (int counter = 1; counter <= intItems; counter++){ if (counter % 13 == 0) continue; total += 3;} MessageBox.Show ("Total for " + intItems + " items is $" + total); }
50
1
51
ListBox in C# ListBox in C#
52
1 If one value at a time is good, then several values at a time must be better. The list controls—ComboBox, CheckedListBox, ListBox, DomainUpDown, ListView, DataGrid, and TreeView—can show more than one value at a time. Most of the list controls—ComboBox, CheckedListBox, ListBox, and DomainUpDown—show a list of objects exposed by the Items collection A ListBox control provides an interface to display a list of items. Users can select one or multiple items form the list. A ListBox may be used to display multiple columns and these columns may have images and other controls. .
53
Creating a ListBox There are two approaches to create a ListBox control in Windows Forms. Either we can use the Forms designer to create a control at design-time or we can use the ListBox class to create a control at run-time. Design-time: In our first approach, we are going to create a ListBox control at design-time using the Forms designer. To create a ListBox control at design-time, we simply drag and drop a ListBox control from Toolbox to a Form in Visual Studio. After you drag and drop a ListBox on a Form, the ListBox looks like Figure 1. Once a ListBox is on the Form, you can move it around and resize it using mouse and set its properties and events.
54
Figure 1
55
Run-time To create a ListBox control at run-time, we create an instance of the ListBox class, set its properties and add ListBox object to the Form controls. First step to create a dynamic ListBox is to create an instance of ListBox class. ListBox listBox1 = new ListBox(); In the next step, you may set properties of a ListBox control. The following code snippet sets location, width, height, background color, foreground color, Text, Name, and Font properties of a ListBox: listBox1.Location = new System.Drawing.Point(12, 12); listBox1.Name = "ListBox1"; listBox1.Size = new System.Drawing.Size(245, 200); listBox1.BackColor = System.Drawing.Color.Orange; listBox1.ForeColor = System.Drawing.Color.Black;
56
1 Once the ListBox control is ready with its properties, the next step is to add the ListBox to a Form. To do so, we use Form.Controls.Add method that adds ListBox control to the Form controls and displays on the Form based on the location and size of the control. The following code snippet adds a ListBox control to the current Form. Controls.Add(listBox1);
57
Setting ListBox Properties
The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item.
58
1 Name: Location, Height, Width and Size:
Name property represents a unique name of a ListBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a ListBox control:listBox1.Name = "ListBox1"; Location, Height, Width and Size: The Location property takes a Point that specifies the starting position of the ListBox on a Form. You may also use Left and Top properties to specify the location of a control from the left top corner of the Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. listBox1.Location = new System.Drawing.Point(12, 12); listBox1.Size = new System.Drawing.Size(245, 200);
59
2 Font Background and Foreground
Font property represents the font of text of a ListBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options :listBox1.Font = new Font("Georgia", 16); Background and Foreground BackColor and ForeColor properties are used to set background and foreground color of a ListBox respectively. If you click on these properties in Properties window, the Color Dialog pops up. Alternatively, you can set background and foreground colors at run-time. listBox1.BackColor = System.Drawing.Color.Orange; listBox1.ForeColor = System.Drawing.Color.Black;
60
ListBox Items The Items property is used to add and work with items in a ListBox. We can add items to a ListBox at design-time from Properties:
61
1 When you click on the Collections, the String Collection Editor window will pop up where you can type strings. Each line added to this collection will become a ListBox item.
62
2 Most of the list controls—ComboBox, CheckedListBox, ListBox, and DomainUpDown—show a list of objects exposed by the Items collection. You can programmatically add items by calling the Add methods defined in the items collection of an existing ListBox object. This method accepts a system.object parameter, which means you are free to add any type of object to the collection. When the object appears in the listBox, its toString representation appears. Example 1: listBox1.Items.Add(“asd1"); listBox1.Items.Add(“asd2"); listBox1.Items.Add(“asd3"); listBox1.Items.Add(“asd4");
63
1 Example 2: Example 3: listBox1.Items.Add(bday);
DateTime bday = DateTime.Parse(" :02pm"); listBox1.Items.Add(bday); Example 3: Person[] boys = { new Person("Tom", 7), new Person("John", 8) }; foreach( Person boy in boys ) { listBox1.Items.Add(boy); }
64
2 class Person { string name; int age; public Person(string name, int age) { this.name = name; this.age = age; } public string Name { get { return name; } set { name = value; } public int Age { get { return age; } set { age = value; }
65
3 You can also add an array of objects to the ListBox by calling the AddRange method on the items collection. Example 1: System.Object[] ItemObject = new System.Object[10]; for (int i = 0; i <= 9; i++) { ItemObject[i] = "Item" + i; } listBox1.Items.AddRange(ItemObject); Example 2: The following code copies all the items from one ListBox control to another: ListBox1.Items.AddRange(ListBox2.Items);
66
4 To Remove an item from a ListBox, call Remove method on the items collection. The remove method uses the properties of object equality to find the object within the collection. For instance, using string objects, it looks for the item with the same string value. Remove has one argument that specifies the item to remove. ListBox1.Items.Remove("Tokyo") You can also remove an item by its position by calling the RemoveAt method. This method uses the zero-based index of the item in the collection as its parameter. To remove all items in s ListBox, call the clear method. RemoveAt removes the item with the specified index number. // To remove item with index 0: ListBox1.Items.RemoveAt(0); // To remove "Tokyo" item: ListBox1. Items.Clear();
67
The commonly used properties
68
1
69
The useful methods
70
Example
71
Selected Text and Item A ListBox supports a few different selection methods. To specify the allowable selection a user can make, change the SelectionMode property using a value from the SelectionMode enumerated data type. SelectionMode property defines how items are selected in a ListBox. The SelectionMode value can be one of the following four SelectionMode enumeration values. None - No item can be selected. One - Only one item can be selected. MultiSimple - Multiple items can be selected. MultiExtended - Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections.
72
1 In a multiple-selection list box, you can determine which items are selected by accessing the SelectedItems or SelectedIndices collection. In a singleselection list box, you can reference the SelectedItem or SelectedIndex properties. Text property is used to set and get text of a ListBox. The following code snippet sets and gets current text of a ListBox: MessageBox.Show(listBox1.Text); We can also get text associated with currently selected item by using Items property: string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
73
2 SelectedText property gets and sets the selected text in a ListBox only when a ListBox has focus on it. If the focus moves away from a ListBox, the value of SelectedText will be an empty string. To get current text in a ListBox when it does not have focus, use Text property. To select an item in a ListBox, we can use the SetSelect method that takes item index and a true or false value where true value represent the item to be selected: listBox1.SelectionMode = SelectionMode.MultiSimple; listBox1.SetSelected(1, true); listBox1.SetSelected(2, true); We can clear all selected items by calling ClearSelected method. listBox1.ClearSelected();
74
3 The Sorted property set to true, the ListBox items are sorted. The following code snippet sorts the ListBox items: listBox1.Sorted = true;
75
Example In this example, we will fill up a list box with items, retrieve the total number of items in the list box, sort the list box, remove some items and clear the entire list box.
76
1
77
2
78
Find Items The FindString method is used to find a string or substring in a ListBox. The following code snippet finds a string in a ListBox and selects it if found. private void FindItemButton_Click(object sender, EventArgs e){ listBox1.ClearSelected(); int index = listBox1.FindString(textBox1.Text); if (index < 0){ MessageBox.Show("Item not found."); textBox1.Text = String.Empty; }else { listBox1.SelectedIndex = index; }
79
SelectedIndexChanged Event Hander
SelectedIndexChanged event is fired when the item selection is changed in a ListBox. The following code snippet defines and implements these events and their respective event handlers. You can use this same code to implement event at run-time: listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged); private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e){ MessageBox.Show(listBox1.SelectedItem.ToString()); } Now every time you change the selection in the ListBox, you will see the selected item displayed in a MessageBox.
80
Data Binding DataSource property is used to bind a collection of items to a ListBox. The following code snippet is a simple data binding example where an ArrayList is bound to a ListBox. private void DataBindingButton_Click(object sender, EventArgs e){ ArrayList authors = new ArrayList(); authors.Add(“asd1"); authors.Add(“asd2"); authors.Add(“asd3"); authors.Add(“asd4"); listBox1.Items.Clear(); listBox1.DataSource = authors; }
81
1 If you are binding an object with multiple properties, you must specify which property you are displaying by using the DisplayMember property. listBox1.DataSource = GetData(); listBox1.DisplayMember = "Name";
82
C# ComboBox Control A ComboBox control is a combination of a TextBox and a ListBox control. Only one list item is displayed at one time in a ComboBox and other available items are loaded in a drop down list. Creating a ComboBox We can create a ComboBox control using a Forms designer at design-time or using the ComboBox class in code at run-time. Every things exactly like the ListBox, except few things.
83
Example-Getting All Items
To get all items, we use the Items property and loop through it to read all the items. The following code snippet loops through all items and adds item contents to a StringBuilder and displays in a MessageBox. private void GetItemsButton_Click(object sender, EventArgs e){ StringBuilder sb = new StringBuilder(); foreach (string name in Combo1.Items) { sb.Append(name); sb.Append(" "); } MessageBox.Show(sb.ToString());
84
DropDownStyle DropDownStyle property is used to gets and sets the style of a ComboBox. It is a type of ComboBoxStyle enumeration. The ComboBoxStyle enumeration has following three values. Simple - List is always visible and the text portion is editable. DropDown - List is displayed by clicking the down arrow and that the text portion is editable. DropDownList - List is displayed by clicking the down arrow and that the text portion is not editable. comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; DroppedDown If set true, the dropped down portion of the ComboBox is displayed. By default, this value is false.
85
C# PictureBox Control The Windows Forms PictureBox control is used to display images in bitmap, GIF , icon , or JPEG formats.
86
Creating a PictureBox PictureBox class represents a PictureBox control. The following code snippet creates a PictureBox, sets its width and height and adds control to the Form by calling Controls.Add() method: PictureBox imageControl = new PictureBox(); imageControl.Width = 400; imageControl.Height = 400; Controls.Add(imageControl);
87
1 You can set the Image property to the Image you want to display, either at design time or at run time. You can programmatically change the image displayed in a picture box, which is particularly useful when you use a single form to display different pieces of information. pictureBox1.Image = Image.FromFile("c:\\testImage.jpg"); Or: Bitmap image = new Bitmap("C:\\Images\\Creek.jpg");
88
SizeMode The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls the clipping and positioning of the image in the display area. pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; There are five different PictureBoxSizeMode is available to PictureBox control. AutoSize - Sizes the picture box to the image. CenterImage - Centers the image in the picture box. Normal - Places the upper-left corner of the image at upper left in the picture box StretchImage - Allows you to stretch the image in code
89
1 The PictureBox is not a selectable control, which means that it cannot receive input focus. The following C# program shows how to load a picture from a file and display it in streach mode.
90
Directory Class Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. Use the Directory class for typical operations such as copying, moving, renaming, creating, and deleting directories. To create a directory, use one of the CreateDirectory methods. To delete a directory, use one of the Delete methods. To get or set the current directory for an app, use the GetCurrentDirectory or SetCurrentDirectory method. To manipulate DateTime information related to the creation, access, and writing of a directory, use methods such as SetLastAccessTime and SetCreationTime.
91
1 To get file names from the specified directory, use static method Directory.GetFiles. Get files from directory: Method Directory.GetFiles returns string array with files names (full paths). using System.IO; string[] filePaths = Get files from directory (with specified extension): You can specify search pattern. You can use wildcard specifiers in the search pattern, e.g. „*.bmp“ to select files with the extension or “a*“ to select files beginning with letter ”a“. string[] filePaths = Directory.GetFiles( @"c:\MyDir\", "*.bmp");
92
2 Get files from directory (including all subdirectories):
If you want to search also in subfolders use parameter SearchOption.AllDirectories. string[] filePaths = "*.bmp", SearchOption.AllDirectories); Delete all files using System.IO; string[] filePaths = foreach (string filePath in filePaths) File.Delete(filePath);
93
FolderBrowserDialog Class
This class provides a way to prompt the user to browse, create, and eventually select a folder. Use this class when you only want to allow the user to select folders, not files. Browsing of the folders is done through a tree control. Only folders from the file system can be selected; virtual folders cannot. Typically, after creating a new FolderBrowserDialog, you set the RootFolder to the location from which to start browsing. Optionally, you can set the SelectedPath to an absolute path of a subfolder of RootFolder that will initially be selected. You can also optionally set the Description property to provide additional instructions to the user. Finally, call the ShowDialog method to display the dialog box to the user. When the dialog box is closed and the dialog box result from ShowDialog is DialogResult.OK, the SelectedPath will be a string containing the path to the selected folder.
94
1 You can use the ShowNewFolderButton property to control if the user is able to create new folders with the New Folder button. FolderBrowserDialog is a modal dialog box; therefore, when shown, it blocks the rest of the application until the user has chosen a folder. When a dialog box is displayed modally, no input (keyboard or mouse click) can occur except to objects on the dialog box. The program must hide or close the dialog box (usually in response to some user action) before input to the calling program can occur.
95
2
96
Example Load all images in a specific directory into a listbox and use its SelectedIndexChanged to select an image and display it in a picturebox.
97
1
98
2
99
OpenFileDialog OpenFileDialog allows users to browse folders and select files. It is available in Windows Forms and can be used with C# code. It displays the standard Windows dialog box. The results of the selection can be read in your C# code. This dialog can be customized to show the file type, beginning directory, and the title to be displayed on the dialog itself. When you limit the file type to just the extension .txt as we did in this sample code, only those particular file types will be visible to the user although they do have the option to select All files (*) as well.
100
1
101
2 Because the OpenFileDialog is an object, we create a new instance by declaring a variable with the data type OpenFileDialog and setting it equal to the new instance. OpenFileDialog dialog = new OpenFileDialog(); Now we set the file type we want to be available to the user. In this case, text files: dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; Next is the starting directory for the dialog and the title for the dialog box are set. dialog.InitialDirectory = "C:"; dialog.Title = "Select a text file";
102
3 Once the dialog properties are set, it is ready to present to the user. if (dialog.ShowDialog() == DialogResult.OK) strFileName = dialog.FileName; if (strFileName == String.Empty) return; //user didn't select a file to opena If the user selected a file, then the DialogResult property value will be "OK" and we will also have the file name and path of that file.
103
Example private void btn_browse_Click(object sender, System.EventArgs e){ try { OpenFileDialog open = new OpenFileDialog(); open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp"; if (open.ShowDialog()==DialogResult.OK) { string filename = openFileDialog.FileName; picBox.Image = Image.FromFile(filename); pictureBox1.Image = Image.FromFile(f openFileDialog.FileName); } catch (Exception) { throw new ApplicationException("Failed loading image");
104
FlowLayoutPanel FlowLayoutPanel simplifies how controls are arranged. With FlowLayoutPanel, we have the controls flow like text from left to right, top to bottom, or the opposite directions. No pixel-based positioning is required for these controls.
105
Add & Anchor You can add controls to the FlowLayoutPanel by dragging controls such as Button, Label, CheckBox and TextBox to the inner part of the FlowLayoutPanel. It is usually a good idea to anchor your FlowLayoutPanel to other parts of the Form. I typically anchor controls to the top, right, left and bottom of the form to ensure they resize when the window is resized by the user or other code. FlowDirection: The unique feature of the FlowLayoutPanel is its support for flowing in different directions. The default flow direction is left to right, like English text. The introductory screenshot in this article shows the FlowDirection of TopDown. For the FlowDirection property, you can also use RightToLeft and BottomUp values.
106
1 AutoScroll In some programs, the FlowLayoutPanel may end up being too small to show all the controls. In this case, you can set the AutoScroll property to True. The FlowLayoutPanel will display scrollbars when the controls overflow.
107
Example-Image List
108
1
109
2
110
3
111
4
112
Check Box Check box controls are inclusive controls used to control the value of a Boolean variable. In most cases, the check box is either checked (true) or unchecked (false). However, a check box can also have an indeterminate state, which is shown as a grayed-out check in the check box, as shown below:
113
1 The Checked property of a CheckBox control lets you know whether a check box is checked. To perform an action when the check box is clicked, you can handle the CheckedChanged event. A check box can also have three states if the ThreeState property is set to true. In addition to the checked and unchecked states, a three state check box also has an indeterminate state. For these check boxes, you can view the state using the CheckState property. This property contains a value in the CheckState enumerated data type. Additionally, when a three-state check box's state changes to the CheckState.Indeterminate state, which visually appears as a gray check box that is checked, the CheckedChanged event is not thrown. However, you can create an event handler for the CheckStateChanged event.
114
Radio Buttons Radio buttons are similar to check boxes in that a radio button can either be checked or unchecked. The differences lie in the relationship between other like controls. Check boxes are inclusive, meaning that the state of one check box does not directly affect the state of another check box unless you programmatically make it so. In other words, two check boxes can be checked at the same time. Radio buttons, on the other hand, are mutually exclusive. Given a group of radio buttons, only one of them can be checked at one time. When a user clicks on a single radio button from a group of radio buttons, the state of that radio button changes to checked and any other radio buttons are set to unchecked.
115
1 Because radio button groups are mutually exclusive, you need to separate each group using a control container. Some of the possible control containers include the GroupBox, Panel, and a Windows Form itself. Determine which container you want to use and perform a drag and drop operation from the toolbox onto your Windows Form. GroupBox controls have been used since the beginning of Windows and are still valuable to this day. A GroupBox control uses a label and border around the controls it contains. A Panel control is a new control designed for the .NET Framework. By default, a Panel control is invisible during runtime and is simply a control container. You can, however, change a Panel control's properties such as its BackColor to give a visual indication to the user that a group of controls is related. To create a group of radio buttons within the control container you just created, drag each individual radio button in the group and drop it on the control container that you just created.
116
Example If you need to enumerate the radio buttons within a radio button group, you can access the Controls collection of the control container the radio buttons are located on. You should, however, ensure that you perform a type check on each element because the control container might also contain nonradio buttons. The following code enumerates a group of radio buttons. As each control is accessed in the Controls collection, its type is checked using the GetType method defined in the Control class, which all .NET controls derive from, and compares the result of that method call using the typeof operator on the RadioButton class.
117
1 private void UpdateLabels(){
foreach( Control ctrl in groupColor.Controls ){ // determine if radio button if( ctrl.GetType() == typeof(RadioButton) ) { // cast control to RadioButton object RadioButton radio = (RadioButton) ctrl; if( radio.Checked == true ){ labelColor.Text = "Color: " + radio.Text; break; }
118
Example-Pizza Calculator
This project calculates the cost of the programmer's food of choice, pizza, using radio buttons and check boxes. The cost of the pizza is based initially on whether the pizza is a small ($5.00), medium ($7.50), or large ($10.00). There is an additional cost of 50 cents for each topping. The following figure shows the project in action. Because the application user has selected a large pizza ($10.00) with pepperoni and anchovies ($1.00 for two toppings), the total cost is $11.00.
119
4 private void btnCalculate_Click(object sender, EventArgs e) {
const double LARGE = 10; const double MEDIUM = 7.5; const double SMALL = 5; const double TOPPING = 0.5; double dblTotal; if (radLarge.Checked == true) dblTotal = LARGE; else if (radMedium.Checked == true) dblTotal = MEDIUM; else dblTotal = SMALL; if (chkMushroom.Checked == true) dblTotal += TOPPING; if (chkPepperoni. Checked == true) if (chkAnchovy. Checked == true) lblTotal. Text = dblTotal.ToString("c"); }
120
5 Finally, the following code in the Click event procedure of the Clear button returns the application to its default settings (large size, all toppings unchecked, cost blank): private void btnClear_Click(object sender, EventArgs e) { radLarge.Checked = true; radMedium.Checked = false; radSmall.Checked = false; chkMushroom.Checked = false; chkPepperoni.Checked = false; chkAnchovy.Checked = false; 1blTotal.Text = ""; }
121
Example
122
System. Collections. Generic; using System
System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication10{ public partial class Form1 : Form{ public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int tx1,tx2,rs=0; tx1=int.Parse(textBox1.Text); tx2=int.Parse(textBox2.Text);
123
if (radioButton1. Checked) rs = tx1 + tx2; else if (radioButton2
if (radioButton1.Checked) rs = tx1 + tx2; else if (radioButton2.Checked) rs = tx1 - tx2; else if (radioButton3.Checked) rs = tx1 * tx2; else if (radioButton4.Checked) rs = tx1 / tx2; textBox3.Text = rs.ToString(); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.