+ All Categories
Home > Documents > Visual Programming

Visual Programming

Date post: 03-Dec-2014
Category:
Upload: narendra299
View: 119 times
Download: 3 times
Share this document with a friend
Popular Tags:
235
Visual Programming Graphical User Interfaces (GUI) allow a user to interact easily with the program using different visual components. On the early days of the computer world, applications are text based and you type commands and input to make the program useful. You need to memorize a long list of commands to be able to work properly with the program. Modern software applications have graphical user interfaces. But creating a program with a user interface was once a tedious task. For you to even create a simple window that displays a message, you need to type lots of code. Creating an application with a graphical user interface was hard until the arrival of Visual Programming. Visual Programming makes it easy for you to create GUI applications by providing you a “canvas” where you simply drag the controls from the toolbox. Controls are visual elements that compose the GUI. You can interact with these controls to perform their functionality. Examples of controls are buttons, text boxes, labels, check boxes, and radio buttons. The term “visual” in Visual C# was from the concept of visual programming. Microsoft uses the term Windows Forms to represent every window in an application. Visual Studio allows you to create Windows Forms Applications easily. You can then create and design the form in the Design View.
Transcript
Page 1: Visual Programming

Visual Programming Graphical User Interfaces (GUI) allow a user to interact easily with the program using different visual components. On the early days of the computer world, applications are text based and you type commands and input to make the program useful. You need to memorize a long list of commands to be able to work properly with the program. Modern software applications have graphical user interfaces.

But creating a program with a user interface was once a tedious task. For you to even create a simple window that displays a message, you need to type lots of code. Creating an application with a graphical user interface was hard until the arrival of Visual Programming. Visual Programming makes it easy for you to create GUI applications by providing you a “canvas” where you simply drag the controls from the toolbox. Controls are visual elements that compose the GUI. You can interact with these controls to perform their functionality. Examples of controls are buttons, text boxes, labels, check boxes, and radio buttons. The term “visual” in Visual C# was from the concept of visual programming.

Microsoft uses the term Windows Forms to represent every window in an application. Visual Studio allows you to create Windows Forms Applications easily. You can then create and design the form in the Design View.

Figure 1

Figure 1 shows the Design View in Visual C# Express 2010. You can see the form and some controls “drawn” in its surface

Page 2: Visual Programming

You can use Visual Studio’s tools for designing controls such as aligning, anchoring, docking, and resizing controls. Visual programming saves development time and suitable for Rapid Application Development. Other languages that does not support visual programming requires dozens of code before you can even create a simple window that shows a short message.

Creating a Simple Windows Forms Application Open Visual C# Express and go to File > New Project. Then from the list of templates, choose Windows Forms Application. A Windows Forms Application is a type of application that has a graphical user interface. Name the project MyFirstWindowsApplication.

You will be presented with a blank form. The selected tab tells that you are viewing the Form1.cs file in Designer View.

Page 3: Visual Programming

Two code files will be created that represent the form. But for now, we will concentrate on the file that is used to add functionality to the form. The form can be viewed in two modes, the Design View and Code View. The Designer will be shown if you are in design view. You will see here the actual form and any visual and non-visual controls you will add soon.

You can also resize the forms by dragging the resizing handles of the form while in the Design View.

Page 4: Visual Programming

Figure 1 – The resizing handles of the form

Adding Controls to the Form

All the controls are located in the Toolbox. The Toolbox can be accessed via the Toolbox tab located by default at the left of the IDE. If it is not shown, you can go to View > Other Windows > Toolbox. Hover your mouse over or click the Toolbox tab to show the actual Toolbox.

Page 5: Visual Programming

Figure 2

The Toolbox is divided into categories and the most commonly used controls are located in the Common Controls category. To open a category and expose its control, simply click the category. The Toolbox will auto-hide by default. If you don’t want that behavior, then you can click the pin icon beside the close button of the Toolbox.

To add controls to the form, choose a control in the Toolbox and double click it. Alternatively, you can drag the control from the Toolbox to the form. Please note that you can only add controls to the client area of the form. The client area is the blank area of the form. You can delete a control or controls by selecting it in the designer and hitting Delete in your keyboard. Add a button control to the form. Most controls also has resizing handles just like the form itself. Resize and position the button as shown if Figure 3.

Page 6: Visual Programming

Figure 3

Changing the Properties of Controls

You can change certain properties of the form and controls. We use the Properties Window to view and change the value of all the available properties of a selected control in the Design View. Note that some properties are not shown in the Properties Window and can only be accessed in code.

Selecting a control is equivalent to single clicking a control in the Designer. For a demonstration of modifying control properties, select the button in the form, then go to the Properties Window. You can pin the Properties Window if you will be working with it frequently.

Page 7: Visual Programming

Find the Text property and change its value to “Click Me”.

The text inside the button in the Designer will update.

Page 8: Visual Programming

You can also click the form in the Designer and change the Text property. When selecting the form, you need to click on any area of the form but not on the controls it contain.

Adding Event Handlers to Controls

The final part of this tutorial is showing you how to add event handlers to certain events of the controls. Events trigger when certain happenings occur. We put event handlers to an event. Event handling will be discussed in detail in a separate tutorial. Each control has its own default event. For example, the Button control has Click as its default event while the Form control has a default event of Load. Event handlers are methods that is associated with an event, and they execute when the associated event happens.

The easiest way to add an event handler is to double click a control in the Designer. You can only do this if you want to add event handlers to the default event of a control. To demonstrate this, double click the button in the Designer. Visual Studio will automatically create an event handler and attached that event handler to the default event of the double clicked control. Once the event handler is created, you will be taken to the Code Editor, with the cursor positioned inside the generated event handler. All you need to do is type the codes that will run when the event occurs.

Page 9: Visual Programming

Don’t mind the other parts of the code as there will be a seperate lessons that discuss them. Type the following code inside the event handler. Please only type the code inside the event handler of the following code. I included the event handler so you can clearly see where to type the code.

private void button1_Click(object sender, EventArgs e){ MessageBox.Show("You clicked the button!");}

The MessageBox class allows you to call a message box used to prompt user with messages and information. The Show method shows the message box with a specified message. You will learn more about the MessageBox class later. Run the program and click the button. You will be presented with a message window with the message you specified as an argument to the Show method.

Page 10: Visual Programming

Another way of adding event handlers to events of controls especially for non-default events, is by going to the Properties Window. To demonstrate this, let’s add a Load event to the form. Go back to Design View by clicking the Design Tab or using the Shift + F7 shortcut.

Select the form in the designer then go to the Properties Window and find the Events button. It is represented by a thunder bolt icon. If it is not visible, be sure that a control is selected in the Designer.

Page 11: Visual Programming

The Properties Window will now show a list of events for the selected control in the Designer. Find the Load event of the form. Clicking the combo box beside it will show you the list of valid methods for the event that exist in the code of the form. You can then choose which method to attach to this event. We can also create a new event handler by double clicking the selected event in the Properties Window. You will be taken to the Code Editor with the proper event handler created for you. Add the highlighted code.

private void Form1_Load(object sender, EventArgs e){ button1.Text = "Text changed by the Load event";}

This statement will modify the Text property of button in the form. The Load event of the form occurs once the form is finished loading. So when you run the program once more, as soon as the program has finished loading, the text inside the button will be changed.

You have now successfully created an simple event-driven windows forms application using the tools available in Visual Studio and Visual C# Express.

Event Handling Graphical user interfaces in .NET and Visual C# uses event handling mechanism to

handle events that occur while the program is running. Events are behaviors or happenings that occur when the program is running. Event handling is the process of monitoring for certain events to occur, and then executing codes when a specific event happens. Windows forms uses event handling to add functionality and respond with the user. Without event-handling, forms and user interfaces are pretty much useless. This tutorial assumes that you already learned the concepts of delegates and events .

Events are declared using a delegate as a type. Delegates hold references to methods. The following is an example of declaring a delegate and an event.

public delegate void SampleEventHandler(int);

Page 12: Visual Programming

public event SampleDelegate SampleEvent;

Based on the declaration of the delegate, the methods that it can accept must not return a value(void) and accepts a single int argument. We then used this delegate type to create our event.

We will now add event handling to the event. Event handlers are methods that match the delegate type of the event and the ones that will be executed when the event occurs. Event handlers are attached to an event. Attached event handlers are executed when the event occurs. You can attach multiple event handlers to the event and they will all run when the event occurs. To attach an event handler to an event, you first create it. When creating an event handler, be sure that it matches the signiture of the delegate that the event uses. For example, considering the delegate created above which has a return type of void and an int paramater, our event handlers should also have a void return type, and an int parameter (please note that access specifier is not important).

public void ShowMessage(int number){ MessageBox.Show("Hello World");}

We can then attach the event using the += operator like this:

SampleEvent += new SampleEventHandler(ShowMessage);

To activate the event, we call it passing the required arguments the same way we call methods.

SampleEvent(3);

Event Handling in Windows Forms

To demonstrate using events on windows forms, create a new Windows Forms Application and name it EventHandling. Double click the form and Visual Studio will automatically create an event handler and attach it to the Load event of the form. The Load event has a delegate type of EventHandler. Most events of controls have a delegate type of System.EventHandler. The following is the definition of the EventHandler delegate.

public delegate void EventHandler(object sender, EventArgs e)

As you can see with the definition of the delegate, it has no return type and has two parameters, an object and an EventArgs instance. The object sender represents the control that activates the event. We will demonstrate its use later. The second argument is an instance of the EventArgs class. This can be called as the event argument and they contain data about the event that happened. The EventArgs is actually a base class and contains no useful members. Certain events will have event arguments that is derived from EventArgs and contain useful properties that the event handler can use. You will notice that the created event handler by Visual Studio matches the signiture of the EventHandler.

Page 13: Visual Programming

private void Form1_Load(object sender, EventArgs e){

}

If you want to create event handlers manually, then be sure to follow the signiture of the delegate type of the event. Visual Studio propose a naming convention for event handlers, as seen in the generated event handler. When naming event handlers, type the name of the control(specified by its Name property) followed by an underscore and then the name of the event. You can ignore this convention if the event handler will be used by multiple events as we will see later.

Comminicating with the Source Control

You have seen that the EventHandler delegate has two parameters, and the first of them is an object which represents the control that sent the event. Since it is of type object, any control can be a source of the event because every control is derived from the object base class. Since the sender is converted to an object, we need to convert it back to the proper control to access its useful properties. To demonstrate it’s use, add a button to the form. Change the Text property of the button to “Hello World!”.

Double click the button to generate an event handler for its Click event. Like the Load event, the Click event also has a type of EventHandler. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e){ Button source = (Button)sender; MessageBox.Show("The message inside the button is " + source.Text);}

Run the program and click the button. A message box will be shown telling the text inside the button that sent the Click event.

Page 14: Visual Programming

The first line of the event handler converts the sender object to a Button using casting so we can access its Text property. We then call the Show method of the MessageBox class to show the value of the Text property of the button that sent the event.

Event Arguments

The second parameter which actually varies depending on the event, is an event argument. The most common is the EventArgs which is the base class of event arguments. It has no properties you can use in your event handler. To demonstrate an event that has a different event argument, we will use the MouseClick event of the button which is a better version of the Click event. Since it is not the default event, we can access it in the events section of the Properties Window. Be sure that the button is selected in the designer. Click the thunderbolt icon to show the events of the button. We need to remove the Click event handler first so it will not conflict with the MouseClick event. Find the Click event and delete the value next to it. Then find and double click the MouseClick event. The MouseClick event has a different delegate type of MouseEventHandler. It has the same signiture as the ordinary EventHandler delegate but it has a different type for its event argument which is MouseEventArgs. The MouseEventArgs is derived from EventArgs. It contains useful properties such as which button(left or right) of the mouse is clicked, the number of clicked done, how much the mouse wheel was rotated, and the point location of the click relative to the source control. Use the code below for the MouseClick event handler.

private void button1_MouseClick(object sender, MouseEventArgs e){ MessageBox.Show("You clicked at point (" + e.X + ", " + e.Y + ")");}

The code above uses the event argument parameter to access the x and y coordinates of the point where the mouse was clicked. The output below my vary depending on where you click on the button.

Page 15: Visual Programming

There are many more event argument types and each offers useful properties about the event that took place.

Using the Properties Window to Attach Event Handlers

We already know that aside from double clicking controls, we can use the Properties Window to attach event handlers to events. We click the thunderbolt icon to go to the Events section of the Properties Window.

The top combo box is used to select controls in the Designer. This is useful when you can’t select certain controls because they aren’t visible or very small.

Find the desired event. To attach an event handler to an event you can double click the name of the event to generate an event handler for the specified event. Alternatively, if you already have created event handlers, you can click the dropdown button to view all the valid event handlers that match the signiture of the delegate type of the specified event.

Page 16: Visual Programming

Using Identical Event Handlers for Multiple Events

Please note that you can use a single event handler for multiple events that has the same delegate type. To do this, you need to first create the event handler with the proper signiture. Then go to the Events section of the Properties Window and find the events you want. Instead of double clicking, choose the event handler you created. Now find another event and choose the same event handler.

Separating Design and Functionality When we create a new windows form, a class that inherits from

System.Windows.Forms.Form is generated. This class is seperated in two files thanks to the feature called partial classes. Partial classes allows you to seperate definitions of a class in different files within the same project and namespace. With the introduction of partial classes in .NET 3.5, Visual Studio was able to seperate design from functionality. This allows a programmer to concentrate on the functionality of the application. The name of the files will have the following pattern:

FormName.cs FormName.Designer.cs

where FormName is the name of the form, for example, Form1. A third file with .resx extention, is used for resources of the form and will be discussed in a seperate lesson. When we create the form, add controls, and modify properties, all the code is written in a somewhat hidden file with a .Designer.cs extension. If you can’t see it, find the .cs file for the form in the Solution Explorer and click the arrow button beside it.

Page 17: Visual Programming

Double clicking the that file will allow you to see all the codes that were generated by Visual Studio. The code contain methods for disposing and initializing the controls. You can see the controls being declared and properties, such as Location and Text, are set depending on what you specified in the Properties Window. You will also see event handlers being attached to events of controls. If you cant see the code, it is hidden by default and is labeled “Windows Forms Designer generated code”. Just click the plus icon to its left to show it. You will see that the code for initializing the controls and their properties and events is located inside a method called InitializeComponent. This method is called in the form’s constructor located at the main code file for the form’s class. The codes in the Designer file is initially hidden because Visual Studio want’s you to use the Designer and the Properties Window instead of writing all these codes manually.

The MessageBox Class The System.Windows.Forms.MessageBox is a static class that is used to show

message boxes for prompting, confirmation and warning users.  To show a message box, simply call the Show method of the MessageBox class. The simplest version of the Show method is the one that accepts a string message as an argument.

MessageBox.Show("Hello World!");

Page 18: Visual Programming

You can also specify the title of the message box by using another overloaded version of the Show method.

MessageBox.Show("Hello World!", "A Message");

You can also change the buttons that will be shown in the message box if you don’t want to use the default OK button. You can do this by using the System.Windows.Forms.MessageBoxButtons enumeration.

MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OKCancel);

The table below shows the members of the MessageBoxButtons enumeration.

Member Buttons ShownAbortRetryIgnore Abort, Retry, IgnoreOK OKOKCancel OK, CancelRetryCancel Retry, Cancel

Page 19: Visual Programming

Member Buttons ShownYesNo Yes, NoYesNoCancel Yes, No, Cancel

The Show() method returns a value from the System.Windows.Forms.DialogResult enumeration. This is useful to determine what button you pressed in the message box. For example, if you click the “Yes” button in the message box, then the Show() method will return the value DialogResult.Yes.

DialogResult result;result = MessageBox.Show("What is your choice?");

if (result == DialogResult.Yes){ //You pressed the Yes button}if (result == DialogResult.No){ //You pressed the No button}

Please note that the Form class also has a DialogResult property. This is not the System.Windows.Forms.DialogResult.

You can also add an icon for your message box to further imply the purpose of the message. You do this by using the members of the MessageBoxIcon enumeration.

MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

The table below shows the different icons that you can use for your message box.

Icon Member Usage

AsteriskInformation

Used when showing information to the user.

ErrorHand

Used when showing error messages.

Page 20: Visual Programming

Icon Member Usage

Stop

ExclamationWarning

Used when showing warning messages.

Question Used when asking a question to the user.

You can use the MessageBoxIcon.None to indicate that the message box will have no icon.

The MessageBoxDefaultButton enumeration tells which of the button is the default, that is, the one that is pressed when the enter key in the keyboard is pushed. It has only 4 member which are Button1, Button2, Button3, Button4. For example, in a message box that has an OK and a Cancel buttons, using MessageBoxDefaultButton.Button1 will make the OK button as the default. When the message box is shown and you pressed Enter in the keyboard, the OK button is pressed.

MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button1);

Controls Controls are visual components that compose the graphical user interface.

Everything you see in a GUI is a control, including the form itself. Controls are located at the Toolbar grouped inside different categories. Most of the controls inherit from the System.Windows.Forms.Control base class which exposes several properties, methods, and events common to those controls.

Control Properties

The following are some of the useful properties of the Control class.

Properties Description

AnchorSpecifies how the control relocates and resizes whenever the form is resized.

AutoSize If set to true, the control will automatically size itself to fit the contents.

BackColor The background color of the control.

BackgroundImage Allows you to add a background image to the control.

BackgroundImageLayout Specifies the way the background image is placed and resized.

Bottom Gets the distance in pixel between the top of the control’s container and

Page 21: Visual Programming

Properties Description

the bottom of the control.

CausesValidation Specifies whether the control will raise validation events.

ContextMenuStrip Allows you to add a context menu to the control.

Controls A collection of child controls within this control.

Dock Docks the control to one of the edges of the window.

EnabledTells whether the user can interact with the control. Set to false to disable the control.

ForeColorThe foreground color of the control. This is also the font color of the text inside the control.

Height The height of the control in pixels.

LeftGets or sets the distance between the left edge of the control and the left edge of its container.

Location The location of the control relative to its container.

Locked Specifies whether the control can be moved or resized in the designer.

MaximumSize Specifies the maximum size of the control.

Margin Specifies the margin between this control and another control.

MinimumSize Specifies the minimum size of the control.

Name The name of the control. This is used to reference the control in code.

Padding Specifies the interior spacing of the control.

Parent The parent of the control.

RightThe distance between the right edge of the control and the left edge of its container.

Size The size of the control. Composed of Width and Height subproperties.

TabIndex Specifies the number of the control in the tab order of its container.

TabStop Specifies whether the control can be accessed by the tab key.

Tag Used to assign special or useful values about the control.

Page 22: Visual Programming

Properties Description

Text The text shown inside the control.

TextAlign Specifies the alignment of text of the control.

TopThe distance between the top edge of the control and the top edge of its container.

Visible Sets the visibility of the control.

Width The width of the control in pixels.

Figure – Control Properties

The most important property in the table is the Name property. This property allows you to reference the control in code. The following discusses more properties common to most of the controls.

Changing the Background Color of the Control

We use the BackColor property of the control to change the color of the background. Find the BackColor property in the Properties Window and click the drop down button. You will be presented with a window with three tabs. Each tabs presents a different set of color.

The System colors the colors your operating system uses as default colors for controls. The Web tab shows colors that are safe to use for the web. And the Custom tab shows much more colors. Alternatively, you can type the RGB values of the color separated by commas in the text box next to the property.

Page 23: Visual Programming

Adding a Background Image

We can change the background image of a control by using the BackgroundImage property. As an example, let’s change the background image of a form. Go to Properties Window while the form is selected and find the BackgroundImage property.

You will be presented with a window which allows you to choose a resource. For now, choose local resource and browse for an image by clicking the Import button.

Once you choosed an image, click OK. The background image will now show up on the form. The alignment and size of an image may not be what you desired. There is another property called the BackgroundImageLayout property. It accepts values from the System.Windows.Forms.ImageLayout enumeration.

Page 24: Visual Programming

Value Description

None The image will be positioned using its top left corner with no resizing of the image.

TileIf the image is smaller than the client area of the control, the image will be repeated until it fills the form.

Center The image is centered within the controls client area.

Stretch The image will be resized to fit the client area of the control.

Zoom The image will be fitted to the client area of the control without loosing its aspect ratio.

Most of the time, Stretch will work fine. The form below has a background image with an image layout of Stretch.

The Text Property

The Text property defines the text or caption inside the control. The text that the Text property represents varies on different controls. For example, Text property of the form gets or sets the caption located in its caption bar. The Text property of the button represents the Text inside the button. The Text property of a text box represents the text inside the text box. We can use the TextAlign property to align the text in different locations of the control. If you click the TextAlign properties’ drop down box in the Properties Window, you will be presented with a small window that allows you to easily point which location you want the text to be aligned.

Page 25: Visual Programming

Changing the Font of the Control

We can change the font type, color, size, and style of the control by using the Font and ForeColor properties. Let’s use a button control as an example.

To change different font properties of the control, find the Font property in the Properties Window. You will notice a drop down button in its left. Open it up and more properties about the font will be exposed.

Page 26: Visual Programming

The useful once are the Name, which defines the type of font to use, the Size which indicates the size of font, Unit which tells the unit to use for the size of the font, and Italic, Strikeout, Underline and Bold to add styles to the control. Alternatively, you can use the button to the right of the font property to open the Font Window.

Here, you can choose the font type, the font style, the size and add certain effects. You can even see a preview of the font. With these, you can customize the font of the controls.

Page 27: Visual Programming

Enabling and Disabling Controls

We can use the Enabled property to tell whether a control can receive focus and user interaction. We set the property to false to disable the control and true to enable it. When we disable the control, its appearance may change. For example, when we disable a button (setting its Enabled property to false), its color and appearance will change. Note that the change is only visible when you run the form and not in the designer.

When a control is disabled, it will not receive focus or events. For example, if a button is disabled, you cannot click it.

Making Controls Invisible

You can temporarily hide a control by setting the Visible property to false. The Visible property is a boolean property which tells whether the control is visible or not. Setting to false makes the control hidden, and setting it to true makes the control visible. Note that you will only see the

Page 28: Visual Programming

effect when you run the form and not in the designer. This allows you to still select the control in the designer even if the Visible property is set to false.

More about the properties and features of controls will be discussed in the following lessons.

Control Events

The following table shows the some useful events common to most controls.

Event Description

BackColorChanged Occurs when the background color was changed.

BackgroundImageChanged Occurs when the background image was added or changed.

Click Occurs when you click the control with the left mouse button.

ControlAdded Occurs when a child control is added to this control.

ControlRemoved Occurs when a child control was removed from this control.

DoubleClick Occurs when you double click the control.

DragDrop Occurs when the drag drop operation is completed.

EnabledChanged Occurs when the control is enabled or disabled.

Enter Occurs when the control is entered.

FontChanged Occurs when the font properties are changed.

ForeColorChanged Occurs when the fore color of the control is changed.

GotFocus Occurs when the control got the focus.

KeyDownOccurs when a key in the keyboard is pressed while the control has the focus.

KeyPressOccurs when the key in the keyboard is pressed and released while the control has the focus.

KeyUpOccurs when a pressed key in the keyboard is released while the control has the focus.

Leave Occurs when the input focus leaves the control.

LostFocus Occurs when the focus of the control is lost.

Page 29: Visual Programming

Event Description

MouseClick A more advanced version of the Click event.

MouseDoubleClick A more advanced version of the DoubleClick event.

MouseDown Occurs when a button in the mouse is down while inside the control.

MouseEnter Occurs when the mouse pointer enters the control.

MouseHover Occurs when the mouse pointer rests on the control

MouseLeave Occurs when the mouse pointer leaves the control.

MouseMoveOccurs when the mouse pointer moves while inside the bounds of the control.

MouseUpOccurs when a pressed button of the mouse is released while inside the control.

MouseWheel Occurs when you move the mouse wheel while the control has the focus.

Move Occurs when the control is moved.

Paint Occurs when the control is redrawn.

ParentChanged Occurs when the parent control of this control changes.

Resize Occurs when the control is resized.

TextChanged Occurs when the Text property of the control is modified.

Validated Occurs when the control is finished validating.

Validating Occurs when the control is validating.

VisibleChanged Occurs when the Visible property is changed.

We will discuss most of the events above in later chapters.

Control Methods

The following are the most useful methods of the Control class.

Methods Description

BringToFront Brings the control to the front of the z-order.

Page 30: Visual Programming

Methods Description

Contains Tells whether a child control is contained inside this control.

CreateControl Creates a new control and add it to this control.

FindForm Retrieves the form that the control is on.

Focus Sets the focus to this control.

GetContainerControl Gets the control that serves as the container of this control.

Hide Hides the control.

RefreshForces the control to invalidate its client area and immediately redraw itself and any child controls.

Select Activates the control

SendToBack Brint the control to the back of the z-order.

Show Shows a hidden control.

Update Causes the control to redraw the invalidated regions within its client area.

The Control class also offers some methods that allow you to manually trigger events of the control. Such methods starts with On followed by the name of the event. For example, the OnClick event triggers the Click event when called. Note that some events cannot be triggered by user interaction such as the Paint event. If you want to trigger such events, use the methods offered by the Control class. You will learn more about these methods when we delve deeper into the world of C#.

Note that these properties, events, and methods are inherited by most of the controls thanks to inheritance. Therefore, I may not include them again when I present the properties, events, and methods of individual controls unless they are very significant to the control.

Naming Your Controls Always make a habit of naming controls. We name our control using its Name

property. Naming controls follows the guideline for naming variables such as spaces,special characters, and the use of keywords are prohibited. There has been many naming conventions that emerged when it comes to naming controls.

Page 31: Visual Programming

You can name the control depending on its use. For example, a text box use to retrieve the first name of the user can simply be named firstName just like a normal variable. But when naming controls, it is better to prefix the actual names with the name of the control. For example, instead of simply firstName, we can use textBoxFirstName. With that convention, we will know, using IntelliSense, that we are working with a text box or any control.

Another technique used by others is abbreviating the control names. For example, instead of using textBoxFirstName, you can use txtFirstName. The txt is short for text box. There has been a list of abbreviations for every control and you can even use your own abbreviation as long as it is clear to you and to others who will look at your code.

Another naming convention is the reverse of the first one where you place the descriptive name first followed by the type of control and also uses camel casing. For example, a text box for retrieving the first name of the person can be named firstNameTextBox or a button used for calculating can be named calculateButton.

The following lessons use the first naming convention where you simply use the name of the control in camelCasing style followed by a descriptive name. You don’t have to memorize a set of abbreviations or invent one. When you drag a control from the ToolBox, you simply need to remove the number suffix and add a descriptive name. When you are typing and you want to easily find what control you want to work with, simply type what kind of control it is, for example, a text box, and all the text box controls will show up in the IntelliSense. The only downside is some names might become too long. It is still up to you as to what naming convention you are more comfortable to use.

The following gives you some example name depending on the control and its use.

Scenario NameA Button used to confirm a message. buttonConfirm, confirmButton, btnConfirmA TextBox used to accept email address from user.

textBoxAddress, addressTextBox, txtAddress

A Form used for obtaining personal information.

formPersonalInformation, personalInformationForm, frmPersonalInformation

A ComboBox to show a list of products.

comboBoxProducts, productsComboBox, cmbProducts

A RadioButton which tells if a person is male.

radioButtonMale, maleRadioButton, radMale

A MenuItem for saving a file. menuItemSave, saveMenuItem, mnuSaveA CheckBox to subscribe to newletter.

checkBoxSubscribe, subscribeCheckBox, chkSubscribe

It is not necessary to name every control in the form. Controls that will never be accessed in code can be left by their default name. Examples of this are labels that are merely used to label other controls. Have a habit of naming the control after you place them onto the form.

Page 32: Visual Programming

The Windows Form Windows Forms (or simply forms) are the windows you see in a Windows

Application. You can create multiple forms in a single application. Each form inherits the properties and methods of the System.Windows.Forms.Form class. The namespace System.Windows.Forms contains components you will need for creating forms and controls.

The following are the parts of a typical windows form.

At the top, you will find the Caption Bar. The Caption Bar is composed of the icon, the caption, and the control box. The control box contains buttons such as minimizing, maximizing, closing, or a help button. The Client Area is where we add the controls. The border or frame which includes the caption bar, encloses the client area and allows you to resize the form.

The following are some of the useful properties of the Form base class.

Page 33: Visual Programming

Property Description

AcceptButton The button on the form that is pressed when you hit the Enter key.

CancelButton The button on the form that is pressed when you hit the Esc key.

ClientSizeGets or sets the client area of the form. The client area is the portion of the form inside the frame borders.

ControlBoxSpecifies whether to show the control box at the top right portion of the form. The control box contains the buttons minimize, maximize, and close.

Controls A collection of Control objects contained inside the form.

DesktopBounds The size and location of the form in the Window’s desktop.

FontThe font that the form will use. Controls inside the form will inherit this property.

FormBorderStyle The border style of the form.

HelpButtonShows a help button right before the close button of the form. (minimize and maximize buttons should be disabled)

Icon The icon that will be used by the form.

Location The coordinates of the form in the screen.

MainMenuStrip Specifies the main menu to be used by the form.

MaximizeBox Tells whether the maximize box located at the top right is displayed.

MinimizeBox Tells whether the minimize box located at the top right is displayed.

Modal Tells whether the form is modal.

Name The name of the form that is used to reference it in code.

OwnedForms A collection of forms that this form owns.

Owner The form that owns this form.

ShowIcon Tells whether the icon is displayed at the left side of the caption bar.

Size The size of the form.

StartPosition The starting position of the form when it is initially shown.

Text The text shown in the caption bar of the form.

Page 34: Visual Programming

Property Description

Figure 1

Figure 2 shows some useful methods of the Form class.

Method Description

Activate Gives the focus to this form and activates it.

AddOwnedForm Adds a new form that this form owns.

CenterToScreen Centers the position of the form in the screen.

Close Closes the form.

Hide Hides this form.

OnLoad Raises the Load event.

Show Shows the form.

Figure 2

Figure 3 shows the available events for the form.

Event Description

Activated Occurs when the form is activated.

Click Occurs when the form is clicked.

Deactivated Occurs when the form is no longer in focus.

FormClosed Occurs after the form is closed.

FormClosing Occurs when the form is closing. Allows you to halt the closing of the form.

HelpButtonClicked Occurs when the help button is clicked.

KeyPress Occurs when a key on the keyboard is pressed.

Load Occurs when the form is finished loading just before it is displayed.

MenuComplete Occurs when the menu of the form loses focus.

Page 35: Visual Programming

Event Description

MenuStart Occurs when the menu of the form recieves focus.

ResizeBegin Occurs when the form enters resizing mode.

ResizeEnd Occurs when the form exits resizing mode.

Shown Occurs after the form is shown for the first time.

Figure 3

The Form class is a child of the System.Windows.Forms.Control base class so methods and properties from the that class are also inherited by the Form class.

Modifying the Control Box

We use the ControlBox property to hide or show the ControlBox. This is useful when you are planning to disable minimizing or maximizing of control or you want to only close the form through code. The image below shows you how the form will look when you set ControlBox property to false.

If you want to disable only the minimize or the maximize button, then you can use the MinimizeBox and MaximizeBox and set them to false.

Page 36: Visual Programming

The form above has its minimize and maximize box hidden. Unfortunately, you cannot hide only the close button.

Changing Form's Border Style

We can change the border style of the form. For example, let's say you don't want the user to be able to resize the form The default border of the form allow a user to do that. We can set the FormBorderStyle property to different values of the System.Windows.Forms.FormBorderStyle Enumeration.

Value Description

None The form has no border.

FixedSingle The form has a non-resizable single line border.

Fixed3D The form has a non-resizable 3d border.

FixedDialogThe form has a thick, non-resizable, dialog style border that has no minimize or maximize boxes.

Sizable The default. The form has a resizable border.

FixedToolWindowThe form has a non-resizable border that has only a close button. This style is used for tool windows.

SizableToolWindow Same as FixedToolWindow but resizable.

Page 37: Visual Programming

The following are screenshots of forms using different FormBorderStyle.

None

FixedSingle

Page 38: Visual Programming

Fixed3D

FixedDialog

Page 39: Visual Programming

Sizable

FixedToolWindow

Page 40: Visual Programming

SizableToolWindow

Form Icons

We use the Icon property to change the icon displayed at the upper left side of the form. Click the browse button next the Icon property in the Properties Window and find the .ico file which is the file extention for an icon image. The ShowIcon property allows you to hide or show the icon in the caption bar.

Accept and Cancel Buttons

You can add a button control to the form and set them as either an Accept or a Cancel button. You do that using the AcceptButton and CancelButton properties. If a button is an accept button, whenever the user hits Enter while the form is active, that button's Click event will be executed. The Cancel button is activated whenever the Escape key is pressed. Just go to the Properties Window, find the desired property and click the drop down button. You will be presented with the names of all the button control in the form. Choose the desired button. For example, suppose you are creating a login form. You can set the button used for logging in as the Accept button. This way, the user can simply press Enter when he is finished typing the password.

There are many more to discover on windows forms and they will be discussed in later lessons.

The Button Control The Button control (System.Windows.Forms.Button) is commonly used to execute

commands when it is clicked. When a button is clicked, you specify codes that will be used. Buttons are typically used to confirm or cancel an action, to perform different actions, and to open some

Page 41: Visual Programming

more dialogs. The Button control has several properties that you can use. The table below enumerates them.

Property Description

AutoEllipsisSpecifies whether to append dots (…) when the text in the button is too long and can't fit the button.

AutoSize Specifies whether the button will automatically resize to fit its content.

FlatStyle

Determines the style of the button. Popup makes the button flat, and when you hover on the button, the button will pop out. Flat makes the button flat and when you move point your mouse inside the button, the background color of the button changes.

Enabled If set to false, the button cannot be clicked or receive focus.Image An optional image that you can place inside the control.ImageAlign The alignment of the image in the button.Text The caption inside the button.Visible Tells whether the button is visible or not.

Figure 1 – Button Properties

A button is still useless by just editing its properties. It needs to react to events to do some work. The following are the most common events available for the Button control.

Event Description

Click Occurs when you click the button.

EnterOccurs when the control becomes the

active control of the form.

LeaveOccurs when the control becomes

inactive anymore.

LocationChangedOccurs when the location of the

button is changed.

MouseDownOccurs when the mouse pointer is in the button

and the mouse button is pressed down.

MouseEnter Occurs when the mouse enters the button.

MouseHoverOccurs when the mouse stays stationary

in the button for an amount of time.

MouseUpOccurs when you pressed the button and

you let go of the mouse button.

MouseLeaveOccurs when the mouse pointer

leaves the button.

You have already seen the Click event which is the default event for a button. Lets create another application that demonstrates the use of other events. Create a new form and drag a button to the

Page 42: Visual Programming

form from the toolbox. Its not important what text you put for the button. In the properties window, find the Name property and change its value to buttonSample. We will now refer to that button in the code using that name. Our program will demonstrate the MouseEnter and MouseLeave events. To access these events, the easiest way is to go to the properties window and click the button with the lightning symbol.

First, find MouseEnter and double click it. Visual Studio will generate an event handler for you for that specified event. Type the highlighted code inside the method.

private void buttonSample_MouseEnter(object sender, EventArgs e){ buttonSample.Text = "Mouse has entered!";}

After typing the code, return back to the Properties Window and now choose the MouseLeave event and double click it to generate an event handler. Again, type the highlighted code inside the event handler method.

private void buttonSample_MouseLeave(object sender, EventArgs e){ btnSample.Text = "Mouse has left!";}

Now run the program. Roll over your mouse to the button and notice that the text has changed. Take away the mouse pointer from the button and the text of the button will change again.

Page 43: Visual Programming

The Label Control The Label control (System.Windows.Forms.Label) is used to add text to a form that

can be used to show messages, or add labels to identify what other controls’ functionality is. Drag a label control from the toolbox to the form. By default, it will have an initial text. The following properties are the most common ones that you will modify.

Property Description

AutoSizeIf true, the size of the borders of the label controlin the designer will be resized automaticallydepending on the text inside it.

BorderStyle Specifies the type of border around the label.

FontUsed to change the font properties of the text inside the label control.

Text The text of the label.TextAlign The alignment of the text inside the Label control

The Text property is the most important one because the main purpose of the Label control is to show text in the form.

Label1.Text = "Hello World!";

You can modify the Font property to change the font family, font size and many font properties.

Page 44: Visual Programming

There are events that are also available for the Label control, but most of the time, you won’t be needing them.

The TextBox Control The TextBox control (System.Windows.Forms.TextBox) is the most basic means of

input in a windows forms. You give the input data by typing it inside the textbox. The text you type can be accessed by using the Text property of the control. The following table shows some useful properties that you can use for the TextBox control.

Property Description

AcceptsReturnUsed with Multiline. Tells if whether the return key is included in the input. The return will be converted into a \n escape sequence.

AcceptsTabIndicates whether to accept tab as an input. By default, hitting tab will bring the focus to the control with the next TabIndex in the form.

EnabledSet to false to make the text box read-only therefore making the text box act like a label.

Font The font properties that will be used by the textbox.Lines The lines of text in a multiline text box.Multiline Set to true to allow multiple lines in a text box.Text The text inside the text box.PasswordChar Accepts a character that will be used to mask each character typed by the user.ReadOnly Tells whether the text in the form can be edited.Visible Tells whether the text box is visible inside the form.WordWrap Used with Multiline. Set to true to enable automatic wrapping of words.

Figure 1

The following example shows the use of textboxes. Create a new Windows Application project. The program will ask two numbers and then when a button is pressed, the sum is shown using a label. Drag two textboxes to the form and name them textBoxFirstNumber and textBoxSecondNumber. Also drag one label for each textbox indicating their purpose. Drag another label that will be used to show the sum and name it labelSum. Place a Button control and name it buttonAdd. Adjust the position and sizes of the controls to match the layout below.

Page 45: Visual Programming

Double click the button to add an event handler to it’s click event. Type the following codes.

private void buttonAdd_Click(object sender, EventArgs e){ int num1 = Int32.Parse(textBoxFirstNumber.Text); int num2 = Int32.Parse(textBoxSecondNumber.Text); int sum = num1 + num2;

labelSum.Text = "Sum = " + sum;}

The code converts the contents of textBoxFirstNumber and textBoxSecondNumber into integers using the Parse method of the Int32 class and stored them in their respective variables. We require conversion because the Text property is of type string. Their contents is accessed using the Text property. The sum is then determined. The sum is displayed afterwards by assigning it to the Text property of labelSum.

The most useful event of the TextBox is the TextChanged event which occurs when the text inside the textbox is modified. The following program shows an example of using this event.

Create another windows forms application and add a textbox and a label in the form. Name them you can leave their default names right now.

Page 46: Visual Programming

Delete the text of label1 by removing the content of its Text property. Note that it would be hard to select this label now if the AutoSize is set to false so you can select this label using the top combo box of the Properties Window.  The default event of the TextBox control is the TextChanged event so double clicking it will create an event handler for the said event. Add the following code to the event handler.

private void textBox1_TextChanged(object sender, EventArgs e){ label1.Text = textBox1.Text;}

Now run the program and type anything in the text box. Notice that the text of the label copies the text you type in the text box.

When the text inside the textbox is modified, the event handler executes and copies the text inside textbox1 to label1.

By default, a textbox can only handle single line of text. To make it a multiline textbox, simply set the Multiline property to true. Once you do that, you will notice that you can change the height of the textbox in the designer.

You can set the WordWrap property to true to automatically bring the cursor below when it reaches the right edge of the text box. If it is set to false, the the text will continue to the to the right clipping the ones at the left side. You can set the ScrollBar property to Horizontal, Vertical or Both to add scroll bars to a multiline text box. When using a multiline textbox, you can use the Lines property to retrieve the individual lines of text.

Page 47: Visual Programming

If your textbox is expected to accept passwords, then you must set the PasswordChar to something like * to mask each character type in the textbox by the character indicated in the PasswordChar property.

The RichTextBox Control The RichTextBox control (System.Windows.Forms.RichTextBox) is similar to a

TextBox control but it allows you to format different parts of the text inside it. The TextBox control is typcially used to accept text input from the user while the RichTextBox control is used to show formatted text and save it in Rich Text Format (RTF).

Figure 1

Figure 1 shows a difference between a TextBox(top) and a RichTextBox(bottom) controls. Although you can do formatting in a normal text box, it is always applied to all of the text inside it. The RichTextBox control allows you to format parts of the whole text of the control. You can also use a rich text box control to accept input from the user as both TextBox and RichTextBox are derived from TextBoxBase class therefore, they share the most common properties such as the Text property.

The following are some common properties available when using the RichTextBox control.

Page 48: Visual Programming

Property Description

AcceptsTab Specifies whether to accept focus as a result of pressing the tab key.

BulletIndentSpecifies the indentation used in the RichTextBox control when the bullet style is applied to the text.

CanRedoSpecifies a whether there are actions that have occurred within the RichTextBox that can be reapplied.

CanUndoSpecifies whether the user can undo the operations done in a RichTextBox control.

DetectUrlsSpecifies whether to automatically detect and add the target link to urls inside the RichTextBox control.

Lines A collection of individual lines in a RichTextBox control.

ModifiedTells whether the contents of the RichTextBox control has been modified since the last time it was set.

MultilineTells whether the RichTextBox control can have multiple lines of text (true by default).

ReadOnly Tells whether the RichTextBox control is read-only.

RedoActionNameSpecifies the name of the action than can be redone once an undo operation is made and the Redo method is called.

RtfContains the text of of the RichTextBox control including the rich text format (rtf) codes.

Scrollbars Specifies the type of scrollbars to display.

SelectedRtfGets or sets the currently selected rich text format (RTF) formatted text in the control.

SelectedText Gets or sets the selected text within the RichTextBox.

SelectionAlignment Specifies the alignment to apply to the current selection or insertion point.

SelectionBackColor Specifies the background color of the selected text.

SelectionBulletSpecifies whether the bullet style is applied to the current selection or insertion point.

SelectionCharOffset Specifies whether the selected text in the control appears on the baseline, as a

Page 49: Visual Programming

Property Description

superscript, or as a subscript below the baseline.

SelectionColor Specifies the color of the selected text.

SelectionFont Specifies the font that the selected text will use.

SelectionLength Specifies the number of characters of the selected text.

SelectionProtectedTells whether the selected text or all the text after the insertion point is protected.

SelectionRightIndentThe distance (in pixels) between the right edge of the RichTextBox control and the right edge of the text that is selected or added at the current insertion point.

SelectionStart Specifies the starting position of the selection or the insertion point.

ShortcutsEnabled Specifies whether predefined or defined shortcut keys are enabled.

ShowSelectionMargin Specifies whether a selection margin is displayed in the RichTextBox.

Text The plain text inside the RichTextBox control.

UndoActionNameSpecifies the action that can be undone in the control when the Undo method is called.

WordWrap Specifies whether to wrap the text inside the RichTextBox control.

Figure 2 – RichTextBox Properties

The following are some events that you can handle for the RichTextBox control.

Event Description

LinkClicked Occurs when a link was clicked.

Protected Occurs when the user attempts to modified a protected text.

TextChanged Occurs when the text inside the RichTextBox is modified.

SelectionChanged Occurs when the selected text is changed.

Figure 3 – RichTextBox Events

Page 50: Visual Programming

Changing Format of the Selected Text

A lot of the properties of the RichTextBox control is used for the currently selected text. For example, the SelectedText specifies the currently selected text by the user. You can also use the Select method to select texts.

richTextBox1.Select(10, 11);

The first parameter specifies the starting index of the selection and the second parameter specifies the length of the selection starting from the starting index.

Once we have selected a text, we can format the seleted text using more properties that focuses on the current selection. For example, to change the color of the currently selected text, you can use the SelectionColor property or the SelectionBackColor to change its background color.

richTextBox1.SelectionColor = Color.Red;richTextBox1.SelectionBackColor = Color.Yellow;

You can then deselect the selected text by clicking anywhere in the form or by using the DeselectAll method.

richTextBox1.DeselectAll();

Page 51: Visual Programming

Please note that when no text is selected, the effect of the selection properties starts from the insertion point. The insertion point is simply the location of the blinking I-beam which specifies the insertion of text will start there. Every new character that you type will now receive the new format you have specified.

Adding A Selection Margin

The selection margin is the little margin on the left side of the RichTextBox control.

The selection margin (indicated by the arrow) is used to easliy select a single line of text. For example, the screen shot above shows the third line selected by clicking the selection margin space beside it. We can set the SelectionMargin property of the RichTextBox control to show the selection margin.

Adding Scrollbars

To add scrollbars, we use the ScrollBars property which accepts a value from the RichTextBoxScrollBars enumeration. This enumeration contains values Horizontal, which adds a horizontal scroll bar when the length of the line is too long and the WordWrap property is set to false; Vertical, which adds a vertical scroll bar when the number of lines of text doesnt fit the height of the RichTextBox; and Both, which automatically adds horizontal and vertical scroll bar when neccessary. When the SelectionMargin property is set to false, you need to use a different set of enumeration values, ForcedHorizontal, ForcedVertical, and ForcedBoth. To disable scroll bars completely, set it RichTextBoxScrollBars.None.

Page 52: Visual Programming

Changing Alignment of Selected Text

We can use the SelectionAlignment property to change the alignment of the selected text, more properly, the paragraph where the selected text or the insertion point is located. The property accepts a value from the HorizontalAlignment enumeration which includes Left, Right, and Center. It is important to know how paragraphs are made inside the control. Initialily, typing your the first character to the rich text box will create a paragraph. To create the next paragraph, you simply press the Enter or Return key.

Undoing and Redoing

You can specify whether the user can undo or redo operation using the CanUndo and CanRedo properties. Undoing simply reverts the change you have done to the contents of the RichTextBox control while redoing negates the effect of undo and brings back the change you have made to the content. The properties UndoActionName and RedoActionName are used to restrict the undo and redo operation to specific actions only. These properties accepts actions in form of strings. The possible actions are:

Action Description

Typing Typing operation

Delete Delete operation

DragDrop Drag and Drop operation

Cut Cut operation

Paste Paste operation

For example, you can assign the string “Delete” to the UndoActionName property to only allow the user to undo a delete operation.

richTextBox1.UndoActionName = "Delete";

For an unknown reason, Microsoft did not make an enumeration for these properties so you have to strings as actions.

Detecting URL’s

The RichTextBox control has the capability to automatically detect URL’s that are typed or pasted to the control. The DetectUrls property allows the control to automatically detect url’s and create a link to their target web page.  Setting that property to true activates the feature and setting it to false deactivates it. Shown in the image below, you can see that URL’s to website resemble a link and putting your mouse cursor over them will change the cursor to a hand.

Page 53: Visual Programming

Clicking the link opens the website using your default web browser.

Adding Bullets

You can create bullets inside a RichTextBox control. You use the SelectionBullet property and set it to true to indicate that the selected text should became buletted text. The BulletIndent property specifies the distance between the bullet and the starting position of the text. The program below has a button that adds a bullet to the beginning of each selected line, or paragraph or to where the insertion piont is located.

Enabling and Disabling Shortcut Keys

The ShortcutsEnabled property enables or disables shortcut keys such as those for cutting and pasting text to the text box. When this is set to true, the following shortcut keys will be accepted by the RichTextBox control.

Shortcut Function

Ctrl + Z Undo

Ctrl + E Center Alignment of Text

Page 54: Visual Programming

Shortcut Function

Ctrl + C Copy

Ctrl + Y Redo

Ctrl + X Cut

Ctrl + Backspace Deletes an entire word to the left of cursor.

Ctrl + V Paste

Ctrl + Delete Deletes an entire word to the right of the cursor.

Ctrl + A Select All Text

Ctrl + L Left Justify

Ctrl + R Right Justify

Setting ShortcutEanbled to false disables these shortcuts.

Protecting Texts

You have the ability to protect certiain parts of text using the SelectionProtected property which when set to true, protects the currently selected text. A protected text cannot be modifies. When the user tries to modify a protected text, then teh Protected event will trigger. You can handle this event to, for example, show a message telling the user that the text he is trying to modify is protected.

Rich Text Format (RTF)

The Rich Text Format is a document file format that remembers the formatting of your text or document. The normal TextBox control cannot save text formats because it simply contains plain text. The RichTextBox control has the Text and Rtf properties where the Text property contains the plain text of the control while the Rtf property contains the text and the RTF codes used to format the text. The screenshots below show you the formatted text, and the RTF codes behind that formatted text.

Page 55: Visual Programming

The RTF code allows other programs (such as Word) to read the formatting and present to you the formatted text. The SelectedRtf gets the selected text together with the RTF codes associated to it. This allows you to include the format when cutting and pasting formatted texts.

The RadioButton Control The RadioButton control (System.Windows.Forms.RadioButton) is a button that can

be either turned on or off. The radio button is a circular button with a label. You simple click a radio button to change it from off to on or vice versa. When the radio button is turned on, a dot can be seen and when it is turned off, the circle appears empty. Radio buttons are usually used when a user must select one choice from a set of choices. For example, if you want to determine the gender of the user, then you can use two radio buttons labeled Male and Female. Since you used a radio button, you can only choose one of the two. The following are some properties of the radio button control.

Property Description

AppearanceThe radio button can be displayed as a normal button,or a circular button with a label beside it.

Page 56: Visual Programming

Property Description

CheckAlignDetermines the alignment of the button. The default isMiddleLeft, which will show the buttonto the left of the label.

CheckedWhen set to true, the radio button will be inits “ON” state and a dot will beseen inside the button.

TextSets the text inside the label of the radio button.

The radio button has a CheckChanged and Click event. The CheckChanged event is sent when the state of the button is changed. For example if the radio button turns from off to on, then the CheckChanged event will execute. The Click event is sent when the radio button is clicked. By default, clicking a radio button will change its state, which will therefore trigger the CheckChanged event. The difference of the Click event is that you can actually change this default behavior of the radio button. There is a property for the radio button control called AutoCheck which if set to false, clicking the radio button will not change its state, but will sent a Click event and through code, you can manually set the radio button’s Checked property to true. The default event for the radio button is the CheckChanged event, therefore, double clicking a radio button while in the VS/VCE forms designer will generate an event handler for the said event. The following example demonstrates the use of the radio button.

Drag two radio buttons to the form. Name them radioButtonYes and radioButtonNo. Drag a button control, name it buttonShow, and set its text to Show Message.

Double click the buttonShow to generate a handler for its Click event. Write the highligted code inside the event handler.

private void buttonShow_Click(object sender, EventArgs e){ if (radioButtonYes.Checked) MessageBox.Show("You choosed yes!"); else MessageBox.Show("You choosed no!");}

When you click the button, the program will determine which radio button is checked. You can do this by using the Checked property. We used an if statement to determine whether radio button is checked (on). If its not, then the other radio button is checked since there are only two radio buttons in the form and at least one of them is always checked.

Page 57: Visual Programming

The CheckBox Control The CheckBox control (System.Windows.Forms.CheckBox) is also a type of button

and apears as an empty box with a label beside it. By default, when the empty box is clicked, a check will show up inside the box telling that the checkbox control is in its “checked” state. Unlike a radio button, you can check multiple or even all of the checkboxes. The CheckBox control contains similar properties as the radio button control. The following are some properties that are exclusive to the CheckBox control.

Property DescriptionChecked Determines if the check box is checked.CheckState Tells whether the checkbox is Checked, Unchecked.ThreeState If true, the checkbox can accept an Intermediate state.

Unlike the radio button, the CheckBox control can have three states by setting the ThreeState property to true. Those three states are Checked, Unchecked or Intermediate. Intermediate indicates that value of the checkbox is invalid or cannot be determined. The screen shot below shows the appearance of each of the three states.

You can change the state of the control in code by using the CheckState property. The CheckState accepts values from the CheckState enumeration.

checkBox1.CheckState = CheckState.Checked;checkBox2.CheckState = CheckState.Unchecked;checkBox3.CheckState = CheckState.Intermediate;

If the checkbox is set to only accept two states, on or off (by setting ThreeState property to false), then you can simply use the Checked property of the checkbox which accepts either true to make the checkbox checked, or false to make it unchecked.

The default event of the CheckBox control is also the CheckChanged event. But there is a minor difference between the CheckChanged event of the RadioButton and the CheckChanged event of the CheckBox control. If for example ThreeState property of the checkbox is set to true, when a checkbox changes its state from checked to intermediate, the CheckChanged event will not be sent. If you want to trigger an event when the checkbox changes from unchecked to intermediate, then you can use the CheckStateChanged event instead.

Page 58: Visual Programming

The following example demonstrates the use of the CheckBox control. Create a form and drag a label, three checkboxes and a button. Change the texts of the controls and align them properly as seen below.

Name the checkboxes checkBoxSoap, checkBoxShampoo, and checkBoxToothpaste respectively. Name the button buttonCheckOut. No need to name the label since we are not using it in our code. Double click the button and copy the following type the following code inside the event handler.

string items = String.Empty;

if (checkBoxSoap.Checked) items += "\n Soap";if (checkBoxShampoo.Checked) items += "\n Shampoo";if (checkBoxToothpaste.Checked) items += "\n Toothpaste.";

MessageBox.Show("You have bought: " + items);

Launch the program and select some items by checking them. As you check the item, they will be added to the list that will be shown when you click the Check Out button.

In the code, we declared a string variable and initialize it into an empty string by using the Empty property (which contains an empty string) of the String class. We then check if each of the checkboxes are checked, if so add the product represented by a string using the += operator

Page 59: Visual Programming

to concantenate the string to the content of output. We then use a message box to show the final output.

The Panel and GroupBox Controls The Panel control is used to group controls on a form. One good use of a panel is

when you want to group radio buttons. Only one radio button from a set of radio buttons is allowed to be on. By grouping radio buttons, you can have more than one radio button that is turned on. To try this out, drag two panels to the form. It can be found in the Containers tab of the toolbox. Adjust their sizes using the resizing handles. To add a control to a panel, simply put the controls inside it. Place two radio buttons inside each of the panels. Below is how your form should look like in the designer view.

Once you place a control inside a panel, the control becomes the child of the panel. The panel therefore becomes the parent of the control. To better illustrate that relationship, try moving the panel. All controls inside the panel moves with it. The relationship also allows the parent and the child to share the values of common properties. For example, setting the Enable property of the panel to false not only disables the form, but every control inside of it as well.

You could notice that the panel in the designer view is represented by dashed box (by default). This will not be visible when you run the actual program. But you will have an option to add visible borders for the panel. Below are some properties of the Panel control.

Property Description

BorderStyle Sets the border style of the panel.

ControlsA collection of child controls

inside the panel.

EnabledAllows you to disable or enable

a control.

Now run the program. You can now turn two radio buttons from different groups.

Page 60: Visual Programming

The GroupBox control is a similar control but allows you to add captions for each group. You do that by using the Text property of the GroupBox control. The GroupBox control also has a default border.

The ComboBox Control The ComboBox control is another way of allowing a user to choose from a set of

options. The ComboBox control looks like a text box with a button in its right side. When the button is clicked, the ComboBox show a drop-down box containing the list of options/items available. The user can then choose from these options by clicking one of them. The selected option will then be the text inside the ComboBox. The following are some of the properties of the ComboBox control.

Property Description

DataSourceA list of data that the control willuse to get its items.

DropDownHeightThe height in pixels of the drop-downbox in a combo box.

FormatStringThe format specifier characters thatindicate how a value is to be displayed.

Items The items in the combo box.Sorted Specifies whether the items on the

Page 61: Visual Programming

Property Descriptioncombo box should be sorted.

TextThe default text when there is no item selected.

SelectedIndex

Gets or sets the selected index. Every item has an index starting from 0 to (number of items – 1). A value of -1 indicatesthat no item is selected.

SelectedItemGets or sets the item of the currentlyselected item.

The following table are some of the events available for the ComboBox control. The default event isthe SelectedIndexChanged event.

Event DescriptionClick Occurs when the component is clicked.

DropDownOccurs when the drop-down portion of thecombo box is shown

DropDownClosedIndicates that the drop-down portion ofthe combo box has been closed.

SelectedIndexChangedOccurs when the value of the SelectedIndex

property is changed.

The following example shows the basic functionality of a ComboBox control. Place a combo box on a blank form. Name it comboBoxNames by changing the Name property. Go to the Properties Window and find the Items property. You should see a button with three dots in it. Click it to open the String Collection Editor. Alternatively, you can click Edit Items located below the list of properties in the Properties Window.

Page 62: Visual Programming

In the String Collection Editor, type the names show in the figure below then press OK.

Change the Text property of the combo box to “Choose a name” so it will have a default text when no name is chosen. Double click the combo box so VS/VCE will generate an event handler for the SelectedIndexChanged event. Type the following code inside the event handler.

Page 63: Visual Programming

string selectedName = comboBoxNames.SelectedItem.ToString();

MessageBox.Show("Hello " + selectedName);

Run the program and choose a name. The program will greet the name you have selected immediately after you selected that name.

When you selected an option, the SelectedIndexChanged event is triggered. The SelectedItem property contains the data of the currently selected item. We stored the value of it into a string variable by converting the value of the SelectedItem property into a string using the ToString() method since that property returns an object. (Alternativaly you can use the Text property but we used the SelectedItem for demonstration). We then display a text containing the output message.

The SelectedIndex property determines the index of the currently selected item. The first item has an index of 0 and each succeeding items has an index of 1 greater than the previous. The last item has an idex of (number of items – 1). So if you have 10 items, the last index is 9. If no item is selected, then the selected index is -1.

If you want to add the items programmatically or during runtime, you can use the Items property of the ComboBox control. The Items property of type ObjectCollection has an Add method that you can use to add new items to the ComboBox.

string[] names = { "Johnny", "Kenneth", "Mark", "Ralph", "Sussie" };

//Add each names from the array to the combo boxforeach(string name in names){ comboBoxNames.Items.Add(name);}

We created a list of names and stored it in a string array. We then use a foreach loop to add each names to the ComboBox. Alternatively, you can use the DataSource property.

comboBoxNames.DataSource = names;

The DataSource Property can accept a collection or array that the combo box will use to fill its list.

Page 64: Visual Programming

The ListBox Control The ListBox control is used to show a list of strings which you can select. By default,

you can only select one item. The ListBox control is best used if you are trying to display a large number of items. The following are the commonly used properties of the ListBox control.

Property DescriptionColumnWidth Specifies the width of each column if MultiColumn is set to true.DataSource Specifies the source of data that the ListBox will display.Items Contains the items that the ListBox will display.MultiColumn Tells whether the ListBox supports multiple column.SelectedIndex The zero-based index of the selected item.SelectedIndices Contains the zero-based index of each selected item.SelectedItem Returns the selected item as an object.SelectedItems An object collection of the selected items.

SelectionMode

Specifies the number of items you can select at the same time.

 

SelectionMode.None – you cannot select anything SelectionMode.One – you can only select one item

SelectionMode.MultiSimple – you can select multiple items by simply clicking them

SelectiomMode.MultiExtended – you can select multiple items by holding ctrl, shift and arrow keys

ScrollAlwaysVisibleTells whether the scroll bars are always visible regardless of the number of items in the ListBox.

SortedTells whether to sort the items in the ListBox alphabetically or in ascending order.

TextIf you set a string value, the first item that matches will be selected. This property returns the text of the first selected item.

Figure 1 – ListBox Properties

The following are the useful methods you can use.

Methods DescriptionClearSelected() Unselects all selected items of the ListBox.

FindString()Finds the first item in the ListBox that starts with the specified string.

The search starts at a specified index.

Page 65: Visual Programming

Methods DescriptionFindStringExact() Finds the first item in the ListBox that matches the specified string.GetSelected() Tells whether the item in the specified index is selected.SetSelected() Selects or deselects the item at the specified index.

Figure 2 – ListBox Methods

To manipulate the items in the ListBox, we use the Items property which is of type ObjectCollection. You can use the typical collection methods such as Add, Remove, and Clear.

Create a new Windows Form and add a ListBox and a TextBox. Set the TextBox‘s Multiline property to true. Follow the layout shown below.

Name the ListBox listBoxInventory and the TextBox textBoxDescription. Double click the form to add a Load event handler to it. Add the following code.

using System;using System.Collections.Generic;using System.Windows.Forms;

namespace WindowsFormTutorial{ public partial class Form1 : Form { private Dictionary<string, string> products;

public Form1() { InitializeComponent(); }

private void Form1_Load(object sender, EventArgs e) { products = new Dictionary<string, string>();

Page 66: Visual Programming

products.Add("Shampoo", "Makes your hair beautiful and shiny."); products.Add("Soap", "Removes the dirt and germs on your body."); products.Add("Deodorant", "Prevents body odor."); products.Add("Toothpaste", "Used to clean your teeth."); products.Add("Mouthwash", "Fights bad breath.");

foreach (KeyValuePair<string, string> product in products) { listBoxInventory.Items.Add(product.Key); } } }}

Figure 3

We created a Dictionary collection that has a string key, and a string value. Inside the Load event handler of the form, we added some products together with their description to this collection. Using a foreach loop, we add each product’s name to the ListBox‘s Items property. Not that each item in the generic Dictionary collection is of type KeyValuePari<TKey, TValue>. When you run the program, you will see that the five products can now be seen inside the ListBox. Note that if the height of the ListBox is insufficient to display all the items, then a vertical scrollbar will be visible to the right of the ListBox.

Now let’s add an event handler to the ListBox‘s SelectedIndexChanged event. The SelectedIndexChanged event occurs when the index of the selected item is changed. This is the default event of the ListBox so double clicking the ListBox will automatically add an event handler for the said event. Add this single line of code.

private void listBoxInventory_SelectedIndexChanged(object sender, EventArgs e){ textBoxDescription.Text = products[listBoxInventory.Text];}

Page 67: Visual Programming

Now run the program and select a product. It’s corresponding description should display in the text box.

Please note that you can also use the String Collections Editor as shown in the last lesson to add items to the ListBox.

The CheckedListBox Control The CheckedListBox control is similar to the ListBox control except that each item

is represented by a CheckBox control. You can select each item like an ordinary ListBox, but in addition, you can also check the box beside each item.

Figure 1 – Appearance of CheckedListBox Control

Page 68: Visual Programming

The properties and methods of the ListBox control can also be found in the CheckedListBox control. But the CheckedBoxControl has some exclusive properties listed below.

Properties DescriptionCheckedIndices A collection of checked indices of the CheckedListBox control.CheckedItems A collection of checked items.CheckOnClick Specifies whether to check the box of an item if the item is selected.

ThreeDCheckBoxesSpecifies whether the checkbox should be flat(two-dimensional appearance) or normal(three-dimensional appearance).

Figure 2 – CheckedListBox Properties

The following are methods exclusive to the CheckedListBox control.

Methods DescriptionGetItemChecked() Tells whether the item at the specified index is checked.GetItemCheckState() Returns the CheckState value of the item at the specified index.SetItemChecked() Checks or unchecks the item at the specified index.SetItemCheckState() Sets the CheckState of the item at the specified index.

Figure 3 – CheckedListBox Methods

Let’s create an example application that uses the CheckedListBox control. Create a new form and add a CheckedListBox control and name it checkedListBoxProducts. Add a ListBox and name it listBoxShoppingCart. Your form should look like this:

Find the Items property of the CheckedListBox control in the Properties Window. Click the button with three dots to open the String Collection Editor. Add the following values.

Page 69: Visual Programming

Press OK and the items should now appear inside the CheckedListBox.

The default event of the CheckedListBox is the SelectedIndexChanged event which is same as the ListBox. What we want to do is add the checked items to the shopping cart. The CheckedListBox control has an ItemCheck event which occurs when the check state of one of the items is changed. Since this event is not the default event of the CheckedListBox, we can’t simply double click the control. We need to go the the Events portion of the Properties Window and find the ItemCheck event.

Page 70: Visual Programming

Double click the ItemCheck to create an event handler for this event. Now add the following code.

private void checkedListBoxProducts_ItemCheck(object sender, ItemCheckEventArgs e){ if (e.NewValue == CheckState.Checked) listBoxShoppingCart.Items.Add(checkedListBoxProducts.Items[e.Index]); else if (e.NewValue == CheckState.Unchecked) listBoxShoppingCart.Items.Remove(checkedListBoxProducts.Items[e.Index]);

}

Inside the event handler for the ItemCheck event has a second parameter of type ItemCheckEventArgs which containts the properties CurrentValue, NewValue, and Index. The CurrentValue property is the CheckState value of the item that triggered the event before it was changed. The NewValue property is the new CheckState value of the item. The Index property is the zero-based index of the item. We test if the NewValue of the item is checked, and if it is, we add that item to the shopping cart. If the NewValue is unchecked, then we remove the item from the shopping cart.

Page 71: Visual Programming

The NumericUpDown Control The NumericUpDown control is typically used to get numeric inputs and

automatically restricts user for giving invalid non-numeric values. The NumericUpDown control appears like a TextBox control but there are arrow buttons on its right or left side that is used to increment or decrement the value of the control.

The numeric value of the NumericUpDown control can be accessed or retrieved using the Value property which is of type decimal. The following are some of the properties of the NumericUpDown control.

Property DescriptionDecimalPlaces Indicates the number of decimal places to display.

HexadecimalIndicates whether the NumericUpDown control should display its value in hexadecimal.

IncrementIndicates the amount that will be incremented or decremented to the current value when the arrow buttons are pressed.

InterceptArrowKeysIf set to true, you can use the arrow keys in your keyboard to increment or decrement the value.

Maximum Indicates the maximum value that the NumericUpDown control can contain.Minimum Indicates the minimum value that the NumericUpDown control can contain.

ThousandsSeperatorIndicates whether the value will be displayed with thousands seperator. (example: 1,000)

Page 72: Visual Programming

Property Description

UpDownAlignIndicates where the arrow buttons are positioned. Set to Right to place the buttons to the right side and Left to place them to the left side.

Value The current value of the NumericUpDown control.

Figure 1 – NumericUpDown Control Properties

The default and most useful event of the NumericUpDown control is the ValueChanged event which executes whenever the Value property of the NumericUpDown control is changed.

Let’s create an example program which uses the NumericUpDown control. Create a new Windows Forms Application and name it NumericUpDown Demo. Add two labels, and two NumericUpDown controls. Change the text of the labels to “Price” and “Quantity” respectively. Add a Button control and change its caption to “Calculate”. Align the controls as shown in Figure 2.

Figure 2

ChChange the properties of the following control:

Control Property Valuebutton1 Name buttonCalculate

numericUpDown1

Name numericUpDownPriceDecimal 2Increment 0.50Maximum 10000

numericUpDown2Name numericUpDownQuantityMaximum 100

Figure 3

The numericUpDownPrice control’s Decimal property was set to 2 so it can have a precision of 2 decimal places. It’s Increment property is set to 0.50 so every increments or decrements adds or subtracts the value by 0.50. The Maximum property indicated was 10000, so the price is limited

Page 73: Visual Programming

to this amount. The numericUpDownQuantity controls Maximum value was set to 100 so you can only order a maximum of 100 items.

Double click the button and to add an event handler to its Click event. Add the following code:

private void buttonCalculate_Click(object sender, EventArgs e){ decimal price = numericUpDownPrice.Value; int quantity = (int)numericUpDownQuantity.Value; decimal total;

total = price * quantity;

MessageBox.Show(String.Format("The total price is {0:C}", total));}

Figure 4

Run the program. Try incrementing or decrementing the values of the numericUpDownPrice and you will see that it increments at 0.50 interval.

Click the Calculate button and the program determines the total price by multiplying the Values of both NumericUpDown control.

The PictureBox Control

Page 74: Visual Programming

You can display images on your form by using the PictureBox control. It is a simple control which has a main purpose of displaying images. All you have to do is browse for the desired image and Visual Studio/VCE will import it to your project. You can use several image formats such as JPEG, GIF, PNG, and BMP.

The following are the useful properties of the PictureBox control:

Properties Description

ErrorImageThe image that will be displayed when the loading of the actual image failed or is canceled.

Image The image that will be displayed by the control.ImageLocation The path of the image to be displayed by the PictureBox.InitialImage The image that is initially displayed while the main image is loading.

SizeModeTells how the image will be displayed. Accepts values from the System.Windows.Forms.PictureBoxSizeMode

WaitOnLoad If set to true, blocks all interaction to the form while the image is being loaded.

Figure 1 – PictureBox Properties

To display an image using the PictureBox control, there are multiple ways you can use. You can go to the Properties Window and find the Image property. Click the button to the right of it to bring out the Select Resource Dialog.

Page 75: Visual Programming

You have to choices, to import the image to the control’s resouce file (Local resource) or to the project’s resouce file. Research files are used to store resources that the application will use. Both choices has an Import button that will allow you to browse your desired image. Once you have picked the image, VS/VCE will import that image to the control or project’s resource file. Your image will now display inside the PictureBox. Note that you can use the ImageLocation property instead which requires the path of your image inside your hard drive. You can even use an image url which is located in the web.

Once the image is displayed, it may not look like you want it to. If the loaded image is larger the the size of the PictureBox, then the image will be clpped. You can use the SizeMode property to change the way the image is positioned or resized inside the control. The property uses values from the System.Windows.Forms.PictureBoxSizeMode enumeration which are presented below.

PictureBoxSizeMode Description

NormalThe image will be positioned in the upper-left corner of the PictureBox and if the image is larger than the PictureBox, the image will be clipped.

StretchImage Resizes the image to match the size of the PictureBox.AutoSize Resizes the PictureBox to match the size of the image.

CenterImageThe image is centered inside the PictureBox. If the image is larger than the PictureBox, the image will be clipped.

ZoomFits the whole image inside the PictureBox w while maintaining the image’s size ratio.

Figure 2 – System.Windows.Forms.PictureBoxSideMode Values

Page 76: Visual Programming

The most common and default event of the PictureBox control is the Click event which is called when the image is clicked.

The LinkLabel Control The LinkLabel control is similar to an ordinary label. But it has an underline and

resembles a link on a webpage. The LinkLabel control can be used to link to files, directories, or web pages. When you place your mouse over the LinkLabel, the mouse pointer will turn into a hand.

The properties of the LinkLabel control is as follows:

Property DescriptionBorderStyle The style of the border around the label.

FlatStyleDetermines the appearance of the LinkLabel. When set to Popup, the button is slightly raised when you hover over it.

LinkArea Indicates Indicates the portion of the text that wil be displayed as a link.LinkColor The color of the unvisited link.

LinksA collection of links that will be displayed. These are not the actual links that will be visited but portions of the LinkLabel that will be displayed as links.

LinkVisitedWhen set to true, the color of the link will be swapped by the color of the VisitedLinkColor property.

TextAlign Specifies the location of the text within the control.VisitedLinkColor The color The color of a visited link.

Figure 1 – LinkLabel Properties

The LinkArea property will allow you to consider only portion of the text as links. The LinkArea requires two values, the starting index and the length. For example, if we only want to consider “C#” as the link, then we can provide values 7 for the index and 2 for the length. You can click the button right next to the LinkArea property in the Properties Window that will bring you to the LinkArea editor. Simply highlight the area you want to be considered as link then press OK.

Page 77: Visual Programming

The Links property allows you to have multiple links within the text. Unfortunately, you can’t access this property in the Properties Window so you have to do it using manual typing of code and values. You can put the code in the Form’s Load event.

private void LinkLabelForm_Load(object sender, EventArgs e){ linkLabel1.Links.Add(new LinkLabel.Link(0, 6)); linkLabel1.Links.Add(new LinkLabel.Link(10, 9));}

The Links property is a collection of LinkLabel.Link objects so we used the Add method and created new instances of LinkLabel.Link class. (Note that Link is a class within the LinkLabel class).

The LinkLabel control must have an event handler hooked to its LinkClicked event. The actual navigation to the desired location is contained in the event handler.

Page 78: Visual Programming

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){ System.Diagnostics.Process.Start("http://visualcsharptutorials.com"); linkLabel1.LinkVisited = true;}

We use the System.Diagnostics.Process.Start static method to open your browser and navigate to the website’s homepage. We then set the LinkVisited property to true to change the color of the link and indicate that it was already been visited. Note that you can also give directory of file paths to open a directory or file.

If you have multiple links inside your LinkLabel control, you can use the Links property of the LinkLabelLinkClickedEventArgs when handling the event to know which link was actually clicked.

private void LinkLabelForm_Load(object sender, EventArgs e){ LinkLabel.Link googleLink = new LinkLabel.Link(0, 6); LinkLabel.Link bingLink = new LinkLabel.Link(11, 4);

googleLink.Name = "Google"; bingLink.Name = "Bing";

linkLabel1.Links.Add(googleLink); linkLabel1.Links.Add(bingLink);}

We created new instances of the LinkLabel.Link class with their respective locations in the LinkLabel. We then attached names to each links using their Name property.

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){ switch (e.Link.Name) { case "Google": System.Diagnostics.Process.Start("http://google.com"); break; case "Bing": System.Diagnostics.Process.Start("http://bing.com"); break; }}

Page 79: Visual Programming

Inside the LinkClicked event handler of the LinkLabel, we get the reference of the Link that was pressed using the Link property of the event argument. Finally, we checked the Name of the link that was clicked so that the browser will open and navigate to the appropriate site.

The MonthCalendar Control The MonthCalendar control (System.Windows.Forms.MonthCalendar) resembles a

calendar and shows a month and all its dates. The MonthCalendar control allows you to choose a month and a date. To choose a month, click the left and right arrows to move the month to the next or previous month.

Clicking the month header, will show all the months of the current year. Clicking the header even further will show all the years of the current decade, and clicking it once more will show all the year of the current century. You can customize the MonthCalendar control using the different properties it offers.

Property Description

AnnualyBoldedDatesA collection of dates of every year that will be displayed as bold in the MonthCalendar control.

Page 80: Visual Programming

Property DescriptionBoldedDates A collection of non-recurring dates that will be displayed as bold.CalendarDimensions Specifies the number of rows and columns of months to display.FirstDayOfWeek Specifies what day the calendar will consider as the first day of the week.MaxDate Specifies the maximum allowable date.MaxSelectionCount Specifies the maximum dates that the user can simultaneously select.MinDate Specifies the minimum allowable date.MonthlyBoldedDates A collection of dates within a month that will be bolded monthly.ScrollChange The number of months to move when clicking the navigation arrows.

SelectionEndIf the user selects a range of date, this property indicates the last date in the range of dates.

SelectionRangeIf the user selects a range of date, this property contains all the dates whithin the range of dates.

SelectionStartIf the user selects a range of date, this property indicates the first date in the range of dates.

ShowToday Specifies whether to show the date today at the bottom of the control.

ShowTodayCircleIf set to true, the date today in the control will be enclosed with a square or a circle.

ShowWeekNumbersSpecifies whether the week number will be shown at the left of each row of the control.

TodayDate The date used by the MonthCalendar as today’s date.

Figure 1 – System.Windows.Forms.MonthCalendar Control Properties

You can bold certain dates annually. For example, you can indicate to bold every 25th of December to indicate Christmas. We use the AnnuallyBoldedDates property which accepts a collection of dates. Simply go to the Properties Inspector, find the property and click the drop down arrow. You will be presented with the DateTime Collection Editor.

Page 81: Visual Programming

Simply click the Add or Remove buttons to add or remove dates. Click an item and you can specify the date by using the Value property inside the Properties Window to the right. Clicking the drop down button shows a date time picker that you can use to choose a date. Alternatively, you can simply type the date inside the text box. The MonthlyBoldedDates property marks dates monthly while the BoldedDates properties marks specific dates only once whithout repeating it monthly or annually.

By default, you can select a maximum of 7 consecutive dates. You do this by holding the Shift key and selecting the first and last dates. You can change the value of MaxSelectionCount property. All the dates between the two selected dates will be selected. If the selected dates exceed the number specified by MaxSelectionCount property, then the number of selected dates will be equal to that property. You can use the SelectionStart, SelectionEnd, and SelectionRange properties to retrieve the dates form the selection. If there is only one date selected, then you can simply use the SelectionStart to retrieve that date.

By default, only one month is shown, that is, 1 column and 1 row. You can change this using the CalendarDimensions property. For example, below shows a 2 by 2 MonthCalendar control which shows 4 months at the same time.

Page 82: Visual Programming

You can handle the events DateSelected and DateChanged. The DateSelected event occurs when a date or a range of dates are selected. The DateChanged event occurs when the user changes the selected date or range of dates.

The DateTimePicker Control The DateTimePicker control (System.Windows.Forms.DateTimePicker) is used to

pick a single date. The control appears by default, as a combo box with a calendar icon at the right part. You can select each date component and such as the month and use the arrow keys to adjust individual components.

Figure 1 – Initial Appearance of a DateTimePicker control

Page 83: Visual Programming

The DateTimePicker control shows (by default) the current date or the selected date. By clicking the calendar icon during runtime, you will be presented with a calendar where you can choose dates.

You can then use this calendar to choose a specific date. You use the left and right navigation arrows to move to the previous or next month.

The initial view of the calendar shows all the days plus some trailing dates of the past and next months. Clicking the Title that displays the month and year changes the view and shows all the available month of the current year.

Page 84: Visual Programming

Clicking the year will show all the years in the current decade and clicking it even more allows you to easily choose dates way back in the past.

There are several properties that allows you to customize the appearance and behavior of the DateTimePicker control.

Property DescriptionCalendarFont Gets or sets the font style applied to the calendar.CalendarForeColor Gets or sets the foreground color of the calendar.CalendarMonthBackground Gets or sets the background of the calendar month.CalendarTitleBackColor Gets or sets the background color of the calendar title.CalendarTitleForeColor Gets or sets the foreground color of the calendar title.CalendarTrailingForeColor Gets or sets the foreground color of the calendar trailing dates.

CheckedThe ShowCheckBox property should be set to false to work with this property. When this value is true, the date in the be changed/updated. When this is false, the selected date cannot be changed.

CustomFormat Accepts a custom format string the will format the date displayed.Format Determines the format of the date displayed by the control.

MaxDateGets or sets the maximum date and time that can be selected in the control.

MinDateGets or sets the minimum date and time that can be selected in the control.

ShowCheckBoxIf true, shows a text box to the left part of the DateTimePicker control. When checked, the selected date can be changed. When unchecked, the selected date cannot be changed.

ShowUpDown

When set to true, shows an up-down button in place of the drop down button. You can’t access the calendar when this is shown. Instead, you need to select a date component and use the up-down arrows to adjust the date.

Page 85: Visual Programming

Property DescriptionValue The currently selected date.

Figure 2 – DateTimePicker Properties

If you are using Windows Vista or Windows 7 and using themes such as Aero, then the properties that modifies the color of the calendar has no effect. To see the results of changing the colors of the calendar, we need to disable Visual Styles. For the sake of demonstration, we will do just that. Find Program.cs in the solution explorer and open it by double clicking it. Comment out or delete the line:

Application.EnableVisualStyles();

Just note that when you do this, the controls will use the old style classic look. You can now change the colors of the calendar using the different properties that modifies the color.

You can change the format of the date displayed using the Format property. You can use the Long, Short, Time, or Custom formats. When the Custom format is selected, you can specify a format string in the control’s CustomFormat property. For example, setting the format to MM-dd-yy shows the date using the month number, the date, and the last two digits of the year where each date component is separated with dashes. Example output would be 04-08-11. For a list of format specifiers for date and time, go here.

The ShowCheckBox property shows indicates whether to show a checkbox at the left side of the control.

Page 86: Visual Programming

When the check box is checked, you can select date or time components and modify them using the arrow keys. If the check box is unchecked, then you are not allowed to do that. Clicking the dropdown button that shows the calendar checks the checkbox. The state of the check box can be accessed using the Checked property.

The ShowUpDown property transforms the dropdown button into an up-down button and hides the calendar icon as shown by the following screen shot.

This will prohibit you from accessing the calendar and limits you to using the up-down button. You select a date or time component and use the up-down button to adjust their values.

We can use the Value property to get or set the selected date of the DateTimePicker control. We can also handle the ValueChanged event of the control to react to changes in date.

The ListView Control The ListView control (System.Windows.Forms.ListView) allows you to show a list

of items in different views and add icons to each of them. The ListView control is composed of ListViewItems which form a grid-like structure of row and columns. Each ListViewItem has a label and the every ListViewItem in the first column can have an icon beside them. One common use of the ListView control is to show a list of files and folders to the user. Figure 1 shows how a ListView will look like.

Page 87: Visual Programming

Figure 1 – ListView Example

You can see that the Windows Explorer uses a ListView to show files and folders. The one shown above uses the Details View, although there are more types of Views available such as Large Icons and Small Icons. The following tables shows some useful properties, methods, and events offered by the ListView control.

Property Description

Activation

Specifies how the user can activate an item in the ListView. Posible values are:OneClick: Activates an item using a single click.TwoClick: Activates an item using double click.Standard: Use the computer’s settings.

Alignment

Specifies the alignment of the items in the ListView. Possible values are:Default: Uses no alignment for the items.Left: Aligns the items to the left of the ListView.Top: Aligns the items to the top of the ListView.SnapToGrid: Creates an invisible grid where the items will snap to it.

AllowColumnReorderSpecifies whether the user can reorder the columns by dragging their column headers to the left or to the right.

AutoArrangeWhen set to true, items will automatically be arranged depending on the Alignment property. The effect can only be seen when using the LargeIcon or SmallIcon Views.

CheckBoxesSpecifies whether to show a checkbox to the left of each item when using the Details View.

CheckedIndices Specifies a collection of indices of checked items.CheckedItems Specifies a collection of checked items.

ColumnsContains a collection of columns for the ListView and allows you to add or remove a column.

FocusedItemContains the item that is selected in the ListView. Returns null if nothing is selected.

Page 88: Visual Programming

Property DescriptionFullRowSelect Specifies whether to select the whole row when an item is clicked.

GridLinesSpecifies whether to draw grid lines when the ListView is using the Details View.

HeaderStyle

Specifies the style of each column header. Possible values are:Clickable: Allows you to click the header just like a button.NonClickable: The header won’t respond to mouse clicks.None: The headers will be hidden.

HoverSelectionSpecifies whether to select an item just by hovering your mouse pointer over it.

Items Contains a collection of Items in the ListView.LabelEdit Specifies whether the user is able to edit the text of an item.

LabelWrapSpecifies whether the labels should wrap over multiple lines to occupy the text.

LargeImageListSpecifies the ImageList control that contains the icons to use when using the LargeIcon View.

MultiSelect Specifies whether the user can select multiple items.Scrollable Specifies whether to show scrollbars.SelectedIndices Contians a collection of indices of selected items.SelectedItems Contains a collection of selected items.

ShowItemToolTipsSpecifies whether to show tool tips for each item that has a ToolTip associated to it.

SmallImageListSpecifies the ImageList control that contains the icons to use when using the SmallIcon View.

Sorting

Allows the ListView to sort the items using one of these possible values:Ascending: Sorts the items in ascending order.Descending: Sorts the items in descending order.None: Do not sort the items.

StateImageList

Specifies the ImageList to use that determines the state of each item. When checkboxes are shown at the left or each item, the two images containd in the ImageList of this property replaces the unchecked and checked appearance of those checkboxes.

TopItem Contains the item at the top of the ListView.

View

Specifies how the items are shown. Possible values are:LargeIcon: Items are displayed using 32×32 icons and a label.SmallIcon: Items are displayed using 16×16 icons and a label.List: Displays the items as a list with icons and labels.Details: Displays multiple columns that can contain information about the each item.Tile: Displays large icon and a label with sub-informations for each of the items.

Figure 2 – ListView Properties

Page 89: Visual Programming

Method Description

BeginUpdateTells the ListView to temporary stop drawing visual updates until EndUpdate() is called which prevents the control from flickering.

Clear Removes all items in the ListView.

EndUpdateSignals the ListView to draw all the updates. You can call this method after calling the BeginUpdate() method.

EnsureVisibleAutomatically scrolls the ListView so the item with the index you specified is shown.

GetItemsAt Gets the ListViewItem specified in position x, y (row, column).

Figure 3 – ListView Methods

Event DescriptionAfterLabelEdit Triggers after the editing of a label.BeforeLabelEdit Triggers before the user begins editing a label.ColumnClick Triggers when the user clicks a column.ItemActivate Triggers when the user activates or selects an item.

Figure 4 – ListView Events

Now that you are familliar with the properties, methods, and events of the ListView control, let’s create a sample application that will demonstrate tha capability of the ListView control. We will create a simple file browser that displays the contents of a specified directory. Each subdirectory will be represented by folders and files will be represented with a blank paper. You need to download the following .ico files that we will use in this exercise.

http://visualcsharptutorials.com/files/folder_file_icons.rar

Extract the contents of the WinRAR file to a location that you can easily find. Create a new windows forms application and name it ListViewDemo. The following shows the GUI for the application that we will create.

Page 90: Visual Programming

Label Type Name Properties

1 ListView listViewFolderFilesView DetailsSmallImageList imageListSmallIconsLargeImageList imageListLargeIcons

2 TextBox textBoxPath Text C:\3 Button buttonGo Text Go4 RadioButton radioButtonLargeIcons Text Large Icons5 RadioButton radioButtonSmallIcons Text Small Icons

6 RadioButton radioButtonDetailsText DetailsEnabled True

7 RadioButton radioButtonList Text List8 RadioButton radioButtonTile Text Tile

Figure 5

After constructing the GUI, we need to create two ImageList controls. An ImageList control is used to contain a collection of images to be used by other controls such as ListView or a menu.

Page 91: Visual Programming

The images contained by the ImageList control should be of the same size. The ImageList control is located in the Components section of the ToolBox so drag two of them to the form. Notice that the controls are added to the component tray since they have no visual representation. Name the controls imageListSmallIcons and imageListLargeIcons.

Figure 6

The imageListSmallIcons will contain small icons and the imageListLargeIcons contains icons that will be shown when the ListView is required to show the items with large icons. Let’s first add the images for the imageListLargeIcons. You will find a small square button with an arrow at the upper right of the control. Click it and change the image size to 32, 32 which means that we will be adding 32×32 pixel images.

Figure 7

Click Choose images to open the Image Collection Editor.

Page 92: Visual Programming

Figure 8

Click the Add button and browse for the folder where you placed the extracted images from the file you downloaded earlier. Select the folder_large.ico and files_large.ico files and click Open. The files will now show up in the Images Collection Editor. The up and down arrows in the middle allows you to change the index of each image which we will use later. Be sure that folder_large.ico is in the index 0.

Page 93: Visual Programming

Figure 9

Click OK to add the images to the imageListLargeIcons. Do the same for the imageListSmallIcons. Leave the size to 16,16 and browse for the folder_small.ico and files_small.ico files. Also ensure that the folder_small.ico is at index 0.

The final step for preparing our GUI is to assign the ImageLists we created to the LargeImageList and SmallImageList properties of the ListView. In the properties window, find the LargeImageList property and click the drop down button then choose imageListLargeIcons. Do the same for the SmallImageList and use the imageListSmallIcons for it. We are now ready to add codes to our application.

Go to the code editor by pressing F7 while in the Designer. Import the System.IO namespace as we will use it later. Write the following method that will create the necessary columns for the ListView control.

1: private void CreateColumns() 2: { 3: ColumnHeader filenameHeader = new ColumnHeader(); 4: filenameHeader.Text = "Filaname"; 5: filenameHeader.Width = 150; 6: listViewFolderFiles.Columns.Add(filenameHeader); 7: 8: ColumnHeader lastAccessTimeHeader = new ColumnHeader("Last Accessed"); 9: lastAccessTimeHeader.Text = "Last Accessed"; 10: lastAccessTimeHeader.Width = 150; 11: listViewFolderFiles.Columns.Add(lastAccessTimeHeader);

Page 94: Visual Programming

12: 13: ColumnHeader sizeHeader = new ColumnHeader("Size"); 14: sizeHeader.Text = "Size"; 15: sizeHeader.Width = 80; 16: listViewFolderFiles.Columns.Add(sizeHeader); 17: }

Figure 10

We created 3 ColumnHeaders for the ListView control. The first column will show the File and Directory names. The second shows the last access time of the file or directory, and the last one shows the size of every file. We also set the sizes of each column to appropriate size to occupy the text of the headers. We then use the Add() method of the Columns property of the ListView to add the headers to the control.

Write the following method which will handle the showing of the files and directories to the ListView.

1: private void ShowItemsOfDirectory(string directory) 2: { 3: DirectoryInfo currentDirectory = new DirectoryInfo(directory); 4: DirectoryInfo[] subdirectories = currentDirectory.GetDirectories(); 5: FileInfo[] files = currentDirectory.GetFiles(); 6: 7: listViewFolderFiles.Items.Clear(); 8: listViewFolderFiles.BeginUpdate(); 9: 10: foreach (DirectoryInfo dir in subdirectories) 11: { 12: ListViewItem item = new ListViewItem(); 13: item.Text = dir.Name; 14: item.ImageIndex = 0; 15: 16: ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem(); 17: subitem.Text = dir.LastAccessTime.ToString(); 18: item.SubItems.Add(subitem); 19: 20: subitem = new ListViewItem.ListViewSubItem(); 21: subitem.Text = String.Empty; 22: item.SubItems.Add(subitem); 23: 24: listViewFolderFiles.Items.Add(item); 25: } 26: 27: foreach (FileInfo file in files) 28: { 29: ListViewItem item = new ListViewItem(); 30: item.Text = file.Name; 31: item.ImageIndex = 1; 32: 33: ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem(); 34: subitem.Text = file.LastAccessTime.ToString();

Page 95: Visual Programming

35: item.SubItems.Add(subitem); 36: 37: subitem = new ListViewItem.ListViewSubItem(); 38: subitem.Text = (file.Length / 1000) + " KB"; 39: item.SubItems.Add(subitem); 40: 41: listViewFolderFiles.Items.Add(item); 42: } 43: 44: listViewFolderFiles.EndUpdate(); 45: }

Figure 11

The method has one parameter which is the path of the directory whose contents will be shown to the ListView. Line 3 creates a DirectoryInfo object based on the directory path passed to the method. We then extracted the subdirectories and files (lines 4-5) using the DirectoryInfo.GetDirectories() and DirectoryInfo.GetFiles() mehtods. Line 7 removes any existing items in the ListView using the Clear() method. In line 8, we used the BeginUpdate() method because we will begin the adding of rows to the ListView control.

Lines 10-25 uses a foreach loop to add every subdirectory of the given directory. Line 12 creates a ListViewItem which represents an item or row in the ListView. We used the Text property and assign the Name of the directory to show the name of the directory as the label for the item. Line 14 specifies the index of the image to use in the assigned ImageLists controls. We used the ImageIndex property of the ListViewItem and assigned zero because we placed the folder icon for both ImageLists at index 0. We then add the FullName which represents the full path of the directory to the Tag property because we will use it later in another method.

Every subsequent column is the ListViewItem‘s subitems. Since we have 3 columns, the last 2 columns are subitems of the first column. Line 16 creates a ListViewSubItem object. Note that ListViewSubItem is an inner class of the ListViewItem so you need to address this class as ListViewItem.ListViewSubItem. Line 17 assigns the LastAccessTime of the directory to the label of the second column. Line 18 adds the subitem to the SubItems property of the ListViewItem. A new instance of ListViewSubItem was created in line 20 for the third column. We won’t be showing the size of every subdirectory so we assigned String.Empty to the Text property of the third column. We also add it to the SubItems proeprty of the ListViewItem. Line 24 finally adds the full constructed ListViewItem to the Items property of the ListView.

Line 27-42 creates another foreach loop to enumerate the files in the given directory. The code is pretty much simillar to the first forloop except that we will now use 1 for the ImageIndex. Line 38 also assigns the size of the file to the label of the third column. Note that the size was converted to KB for a more practical look. After all the files has been added to the ListView, we called to EndUpdate() method to show the changes and the added rows to the ListView.

Modify the Form1() constructor to add some line of code to add codes that call the CreateColumns() and ShowItemsOfDirectory() methods.

Page 96: Visual Programming

1: public Form1() 2: { 3: InitializeComponent(); 4: 5: CreateColumns(); 6: ShowItemsOfDirectory(textBoxPath.Text); 7: }

Line 6 calls the CreateColumns() method we created to create the three columns for our ListView. Line 7 calls the ShowItemsOfDirectory() method and we passed the text of textBoxPath which is initially C:\. Therefore, when you run the program, the contents of C:\ are initially shown.

Go back to Designer and double click buttonGo and use the following event handler for its Click event.

private void buttonGo_Click(object sender, EventArgs e){ ShowItemsOfDirectory(textBoxPath.Text);}

When the user types a directory path in the text box, pressing buttonGo will show the contents of that directory.

Finally, we now need to add event handlers for the radio buttons that changes the view of the ListView control. Double click each of the radio button and simply assign the right View to the View property of the ListView.

private void radioButtonLargeIcons_CheckedChanged(object sender, EventArgs e){ listViewFolderFiles.View = View.LargeIcon;}

private void radioButtonSmallIcons_CheckedChanged(object sender, EventArgs e){ listViewFolderFiles.View = View.SmallIcon;}

private void radioButtonDetails_CheckedChanged(object sender, EventArgs e){ listViewFolderFiles.View = View.Details;}

private void radioButtonList_CheckedChanged(object sender, EventArgs e){ listViewFolderFiles.View = View.List;}

private void radioButtonTile_CheckedChanged(object sender, EventArgs e){ listViewFolderFiles.View = View.Tile;}

Page 97: Visual Programming

Run the program and you will see that the contents of C:\ are initially shown. Type another directory and press Go to check its contents. Change the view of the ListView using the radio buttons to see how each View looks.

Page 98: Visual Programming

The TabControl The TabControl control (System.Windows.Forms.TabControl) allows you to create

tabbed windows that you can see in many applications. An example of a tabbed window are the properties window of files and the tabs in Visual Studio.

Figure 1 – Tabs in Visual Studio

Figure 2 – Tabs in a Properties Window of a file

Page 99: Visual Programming

The TabControl serves as a container to other controls. You can access a tab by clicking it. The appearance of an active tab will change so you can distiguish which tab is activated. Once you click a tab, the controls that belong to it will be shown. The TabControl allows you to properly organize the a form into different tabs where each tabs represents a category. For example, you can place a form that gets personal information on the Personal Info tab and the educational background in the Educational Background tab.

To add a tab control, go to the Containers category of the toolbox and find the TabControl. Drag it to the form. You can resize the control but perhaps the best way is to use the Dock property so it will always take up the whole space of the form. You can go to the Properties window and find the Dock property. Click the drop down then click the middle button which means that the TabControl will be docked to all side of the form.

The TabControl consists of TabPage controls which represents the actual tab and its content. The tab pages of a tab control can be accessed using its TabPages property. The following are some useful methods of the TabPage control.

Property DescriptionControls The controls that are exist inside this TabPage.ImageIndex Gets or sets the index displayed on this tab.

ImageKeyGets or sets the key accessor for the image in the ImageList of the associated TabControl.

Text The text that shows in the tab button of the TabPage.

Figure 3 – TabPage Properties

To add a tab page, you can click the small arrow button located at the upper right side of the TabControl. This will open the smart menu where you can add or remove tab pages.

Page 100: Visual Programming

Alternatively, you can go to properties window and find the TabPages property of the TabControl. Make sure that the TabControl is the control selected and not a TabPage. Click the button of the TabPages property to open the TabPages Collection Editor.

The TabPage Collection Editor allows you to add and remove tabs and change properties such as the text of individual tabs. You can add controls to individual containers of the tab. For example, drag some controls to the body of the first tab. Then you can click on the second tab in the Designer and you can add another set of controls for that tab.

Page 101: Visual Programming

Let us now discuss the TabControl itself. The following are some properties of the TabControl.

Property DescriptionAlignment The area (top, bottom, left, right) where the tabs are aligned. The default is top.Appearance The appearance of the control’s tabs.ImageList Contains a list of images that will be displayed for each tab.ItemSize Specifies the size of the tab.Multiline Allows you to create multiple rows of tabs.SelectedIndex Specifies the index of the selected tab page.SelectedTab Gets or sets the selected tab.TabCount Returns the number of TabPages of the TabControl.

TabPagesAllows you to access the tab pages of the TabControl and add or remove tab pages.

Figure 4 – TabControl properties

The Alignment property specifies where the tabs are located. The default value is Top which displays the tab in the top of the TabControl. The Appearance property changes the appearance of the tabs. It can accept three values such as Normal (the default), Buttons (which makes the tab look like a button), or FlatButtons (buttons that are not popping out). Figure 4 shows the apperances of the tab using different values for the Appearance property.

Page 102: Visual Programming

Figure 4 – TabControl Appreances

The ImageList Property allows you to add image icons to each tab. This property accepts a referecnce to an ImageList control. The ImageList control is commonly used for this property which is also available in other controls such as menus and tree views. We will discuss briefly here how to use the ImageList to provide images to other control, in this case, the TabControl. Drag an ImageList from the toolbox to the form. It is located in the Components section of the Toolbox. The ImageList will then be located in the component tray of the Designer. The ImageList will use the following two images:

Save it to any location in your hard drive. Now click the ImageList control located in the component tray of the Designer. Find the Images property in the Properties Window and click the button beside it. You will be presented with the Image Collection Editor.

Page 103: Visual Programming

Clicking the Add button allows you to browse for an image. Add the two images I have provided then click OK. You must now assign the image list to the ImageList property of the TabControl. Go to the ImageList property of the TabControl and choose the image list we have created. To show this icons beside the tabs of the TabControl, select the individual tab page in the designer (by clicking its body) then go to the Properties Window and find the ImageIndex property. Clicking the dropdown beside it will show you the indexes and a preview of each image. Assign your desired index to each tab. You can use the same index for different tabs. Your tabs will now show images beside the their text.

You can adjust the ItemSize property to adjust the size of tabs. This is useful when the images you placed in tabs are too big.

Page 104: Visual Programming

If the number of tabs is too many and it doesn’t fit the width of the form, then arrow buttons will show up to the top right of the TabControl next to the last visible tab.

You can click the arrows to scroll the tabs to the left or to the right.

The MultiLine property allows you to create multiple columns of tabs. If the tabs are too many, then you can set this property to true.

The TabPages property allows you to add or remove tab pages to the TabControl. The following code programatically adds three more tab pages to the TabControl.

TabPage tab1 = new TabPage("Tab 1");

Page 105: Visual Programming

TabPage tab2 = new TabPage("Tab 2");TabPage tab3 = new TabPage("Tab 3");tabControl1.TabPages.Add(tab1);tabControl1.TabPages.Add(tab2);tabControl1.TabPages.Add(tab3);

The TabPages has a type of TabPageCollection which is a collection of TabPage objects. Therefore, we can use typicall collection methods such as Add, Remove, or AddRange.

You can use the SelectedIndex property to get the index of the selected tab. The index is the position of the selected tab in the TabPages collection.

MessageBox.Show("The selected tab is " + tabControl1.TabPages[tabControl1.SelectedIndex].Text);

The SelectedTab simply returns or sets the selected TabPage object.

TabPage selectedTab = tabControl1.SelectedTab;MessageBox.Show("The selected tab is " + selectedTab.Text);

The TabCount simply returns the number of TabPages of the TabControl.

The TabControl has a SelectedIndexChanged event which triggers when the selected tab changes.

The TabControl is very useful when your form has different sections or categories. A good example where a TabControl will be useful is in a Form that provides the options or settings of an application.

The ToolTip Control You can use the ToolTip control (System.Windows.Forms.ToolTip) to display

tooltips which offers description about the the a certain control of part of the GUI. Tooltips can be seen in numerous applications including Visual Studio. Tooltips give you a brief description to the functionality of a certain GUI component or control.

Page 106: Visual Programming

You can find the ToolTip control in the common controls category. When you drag a ToolTip control from the toolbox to the form, you will find it in the component tray section of the Designer.

Once a tooltip is placed, you need to assign it to a control. Whenever a tool tip is added to the form, a new property named ToolTip is added to every control in the form. You can find it in the properties window.

Page 107: Visual Programming

This new property specifies the text inside the tool tip that will be shown. Each tool tip you add will also add its own property to every control. So if for example, we have two ToolTips control added to the form, then two ToolTip properties will be added to each control.

Let’s take a look at some properties of the ToolTip control.

Property DescriptionActive This property activates or deactivates the ToolTip.AutomaticDelay This affects the value of other delay properties.AutoPopDelay Determines the time the tooltip will stay visible.InitialDelay Determines the time to wait before the tooltip will pop out.IsBalloon Specifies whether the tooltip should use a ballon-styled window.

ReshowDelaySpecifies the length of time that must transpire before subsequent ToolTip windows appear as the pointer moves from one control to another.

ShowAlwaysSpecifies whether a ToolTip window is displayed, even when its parent control is not active.

ToolTipIcon An optional action shown to the left of the tooltip window.ToolTipTitle Adds a title to the tooltip message.UseFading Specifies whether a fade effect should be used when displaying the ToolTip.

Figure 1 – ToolTip Properties

Before a tool tip can be shown, you need to activate it by setting the Active property to true. The AutoPopDelay determines how long the tooltip will stay visible when the mouse is over a control. The InitialDelay property specifies the time the mouse should stay over a control before the tooltip will show. The ReshowDelay specifies the time to wait before the Tooltip will be

Page 108: Visual Programming

reshown when you move from one control to another control. The AutomaticDelay property automatically balances the three previously said properties. When set, the AutoPopDelay will be equivallent to ten times the value of AutomaticDelay. The values of InitialDelay will be equal to the AutomaticDelay and ReshowDelay will have a value which is half the value of AutomaticDelay. Note that these properties accept integers which represents milliseconds.

You can also add a title and an icon in a tooltip window using the ToolTipTitle and the ToolTipIcon properties.

You can also change the appearance of the tooltip window by setting the IsBalloon property to true.

You can add multiple ToolTip controls to the form so each control can use a different ToolTip with a different set of properties. Although a single control can use multiple tooltips at the same, time, it is not practical and looks wiered when the tooltips pop out.

The TrackBar Control

Page 109: Visual Programming

The TrackBar control (System.Windows.Forms.TrackBar) looks like a slider with a thumb that you can move to adjust it’s value. The part where the thumb points represents the current value. The following shows you how a track bar looks like.

Figure 1

The user can slide the thumb to the left or to the right or you can change the orientation to vertical so you can slide the thumb up or down. Each tick marks below represents a value, with the lowest being in the left or bottom, and the highest in the right or top. Let’s take a look at some properties of the TrackBar control.

Property Description

LargeChangeThe value to add or subtract when the user presses the Page Up or Page Down key or when he/she clicks either side of the TrackBar.

MaximumSpecifies the maximum value that the TrackBar can handle. It is also the value of the rightmost or topmost tick.

MinimumSpecifies the minimum value that the TrackBar can handle. It is also the value of the leftmost or bottommost tick.

Orientation Specifies whether the orientation of the TrackBar is Horizontal or Vertical.

SmallChangeSpecifies the value added or subtracted when the user presses the arrow keys to move the thumb of the TrackBar.

TickFrequency Specifies how frequent the ticks will show depending on the range of value.

TickStyle

Specifies the position where the ticks will show. Possible values are:None: Don’t show the ticks.Bottom: Show the ticks at the bottom.Top: Show the ticks at the top.Both: Show the ticks at both top and bottom.

Value Contains the current value specified by the TrackBar.

Figure 2 – TrackBar Properties

The TrackBar control uses the Scroll event to react to the scrolling of the thumb of the TrackBar.

Let’s look at an example program that shows you how to use the TrackBar control. Create a new Windows Forms Application and add three track bars and labels. The TrackBar can be found in

Page 110: Visual Programming

the All Windows Forms section of the Toolbar. Also add a panel control and set it’s BackColor property to Black.

Figure 3

Name the three track bars as trackBarRed, trackBarGreen, and trackBarBlue. Set their Maximum property to 255 and TickFrequency to 15. Switch to Code View and type the following event handler that will be used by the three track bars.

private void trackBar_Scroll(object source, EventArgs e){ int red = trackBarRed.Value; int green = trackBarGreen.Value; int blue = trackBarBlue.Value;

Color color = Color.FromArgb(red, green, blue);

panelColor.BackColor = color;}

Figure 4

Go back to the Designer and select each track bar. Go to the Events section of the Properties Window and find the Scroll event then choose the trackBar_Scroll which is the event handler we created.

Page 111: Visual Programming

Inside the event handler, we used the Value property of each track bar  and stored it to three variables. These three values represent the RGB values of a color. We created a System.Drawing.Color object and used the FromArgb() method with the values of the track bars. We then changed the BackColor of the panel with the new color constructed based on the values of the track bars.

Run the program and slide the different track bars and notice how the color of the panel changes.

The Timer Control The Timer control (System.Windows.Forms.Timer) is used to execute commands

for every tick of time which is specified with an interval. For example, if you wan’t to print your name for every 5 seconds, then you can use the Timer control. The Timer control is a non-visual control and can be seen in the component tray after you drag it to the form from the tool box.

The Timer control doesn’t have that much properties. The two properties that is most important are the Enabled and Interval properties. The Enabled when set to true starts the timer, and stops it when set to false. The Interval property specifies the interval time between calls to the Tick event, which is the default event of the Timer used to execute commands. Note that the value that is accepted by the Interval property is in milliseconds. If you give the value 5000 as the interval, then the Tick event will be called for every 5000 milliseconds or 5 seconds.

Let’s take a look at an example application of the Timer control. The following application has a button that will be animated to move up and down and bounce from the bounds of the client area

Page 112: Visual Programming

of the form. Start by creating a new Windows Forms Application and naming in TimerDemo. Add a button control to the center of the form as seen in Figure 1.

Figure 1

Drag a Timer control to the form. It can be found in the Components section of the tool box. You will notice that it now appears inside the component tray at the bottom portion of the Designer.

Figure 2

Select the timer control in the component tray and change it’s Interval property to 50 and it’s Enabled property to true so the animation will begin the moment the user runs the program. Double click the timer control to generate an event handler for it’s Tick event. Remember that this event handler will be called for every 50 milliseconds. Add the following class member that will hold the number pixels to move for every tick.

private int velocity = 5;

Use the following event handler for the Timer‘s Tick event.

private void timer1_Tick(object sender, EventArgs e){ if (button1.Top <= 0 || button1.Bottom > this.ClientSize.Height)

Page 113: Visual Programming

velocity = -velocity;

button1.Top += velocity;}

Figure 3

The very first that the timer ticks, this handler will be called. It will first test if the button hits the topmost or bottommost corner of the form. To determine if the button hits the top corner, we used the Button.Top property which returns the Y coordinate of the top of the button. If it returns 0 or less, then it means that the button is or beyond the top bound of the client area of the form. Note that the coordinate system used by the form starts it’s origin from the top-left.

The second part of the condition in the if contidion tests if the button hits the bottom bounds of the client area. We used the Button.Bottom property to get the Y coordinate of the bottom of the button. We then check if it exceeds the bottom of the form by comparing it to the Height of the client area of the form. We do this using the Form.ClientSize property and accessing it’s Height property.

If any of the condition is true, then we simply reverse the value of the velocity by using the – operator to multiply the value by -1. This would produce a bouncing effect. If the button is moving up (because it moves 5 pixels up), and it hits the top corner, then the velocity will be inverted and become’s -5. Moving -5 pixels up is equivalent to moving 5 pixels down.

Run the program and see the button bounce from the top and bottom corners of the form.

Designing Windows Forms When designing a user interface, you must consider the location, size, alignment,

and colors. Thankfully, Visual Studio has some tools that will aid you when designing user interfaces.

For the demonstration of these tools, create a new windows forms application. When you are dragging a control to a form, you might notice some lines that appear. The Snap Lines allows you to snap a control to the edges of a form or automatically position your control with respect to the position of other controls.

Page 114: Visual Programming

You can snap a control to the different edges of a form. If there are other controls on the form, the control you are dragging can automatically align itself to other controls.

Page 115: Visual Programming

You can align a control to the top, center, bottom, left, or right of a bigger control.

Page 116: Visual Programming
Page 117: Visual Programming

Visual Studio also has commands to automatically align, and equalize spacing and sizes of controls. Consider a form with multiple controls:

Page 118: Visual Programming

You can select each control that you want to align by clicking them while holding the Shift key. You can also select controls by dragging your mouse and enclosing all the controls that will be selected in the selection box.

Once controls are selected, the control with a white box in its upper left corner will be the source control that other controls will align to. You can align other controls to the different edges of this control. To align controls, go to Format > Align and then choose which edge to align. For demonstration, choose Left. Other controls will now align to the left edge of the source control.

Page 119: Visual Programming

You can also center a control in a form vertically or horizontally. Just go to Format > Center Form and choose which direction you want your control to be centered.

You can also use another command for equilizing the spacing or the distances between controls. Consider this example form:

The form above contains controls that has unequal spacing between each other. To equalize their spacing, Select the controls and then go to Format and choose Vertical Spacing for the spacing

Page 120: Visual Programming

above or below the control, or Horizontal Spacing for the spacing at the left or the right side of the control. Choose Vertical Spacing and then click Make Equal.

The spacing vertical spacing between the controls are now evenly spaced.

You can also select multiple controls and equilize their sizes. Consider another form below:

Page 121: Visual Programming

The control with the white resizing handles will the be the reference control. And other controls will be resized according to the size of this control.

Go to Format > Make Same Size, then you can choose to make all the widths the same, all the height the same, or both. Choose Both all the controls will have the same size as the reference control.

Page 122: Visual Programming

You now know some techniques on making the design of your form neat and uncluttered.

Anchoring Controls One problem when placing controls in a windows form is that their location stays

the same when the form is resized. This could result in a total mess of the forms layout. It will also look very unprofessional. Consider the example below. We created a simple form with several controls in it. When we run the program at first, you will see that nothing is wrong.

But when we resize the form by dragging the sides of the form or hitting the maximize button, you will definitely see the problem.

Page 123: Visual Programming

Note that the image above was resized to fit the page. As you can see, the position of the controls did not adjust accordingly when we resized the form.

One way to fix this is using the Anchor property which are availble to most of the controls. The anchor property tells how the control behaves when we change the size of the form. We can specify if the control will anchor to the different edges of the form. We can also specify how the controls will resize.

Let’s try putting to anchor our controls so they will look natural whatever the size of the form is. The Anchor property accepts a value from the System.Windows.Forms.AnchorStyles enumeration

AnchorStyle DescriptionBottom The control is anchored to the bottom edge of the container.Left The control is anchored to the left edge of the container.Right The control is anchored to the right edge of the container.Top The control is anchored to the top edge of the container.None The control is not anchored to any of the edges of the container.

System.Windows.Forms.AnchorStyles Values

The default anchor of every control is a combination of Top and Left. When we assign AnchorStyles values to the Anchor property of a control, the distance of the control from the particular edge remains the same even if we resize it. For example, let’s anchor a button to its right edge.

Visual Studio/Visual C# Express has a tool for specifying anchor styles. Select the control that will have an anchor. Go to the Properties Window and find the Anchor property.

Page 124: Visual Programming

Click the drop down button and you will be presented with a small window with 4 rectangles on each edge.

The rectangle at the center represents the control. The gray rectangles are the edges where the control will be anchored. You simply click these rectangles to add or remove an AnchorStyle to the control. Let’s try remove the anchor to the Top and Left, and add an Anchor to the Right edge.

Now run the program and try to resize the form. Examine the distance of the button from the right edge when it was not resized and after it is resized.

Page 125: Visual Programming

As you can see, the distance of the control from the right edge regardless of the form’s size is the same. Now lets say we add an anchor style to the Bottom, then we will have a combination of Right and Bottom anchor styles.

Page 126: Visual Programming

With these combination of AnchorStyles, the control will always have the same distance from the right edge of the form and from the bottom edge of the form.

Now what will happen if we specified anchor directions that are againts each other. For example, the Left is against Right. We are expecting that the control will have the same distance from its left and right edge.

Run the program and resize the form.

Page 127: Visual Programming

The button was resized to maintain the two distance from its opposite sides. If anchor the control to all the four sides, the the control will be resized horizontally and vertically to keep its distance on all sides.

The control will have a different behavior when we remove all the anchors (setting the Anchor property to AnchorStyles.None). The control will move half of the amount of resizing done to one side of the form. For example, if we resize the form to the right by 100px, then the control will move to the right by 50px (half of 100). If we resize the form 100px to the right and 50px to the bottom, then the control will move 50px to the right and 25px to the bottom.

Docking Controls The Dock property allows you to dock the control to any of the edges of the form or its

container. Its another way to make your controls intact when you resize the form. When you resize the form, the control remains docked to the edge specified. The Dock property accepts a value from the System.Windows.Forms.DockStyle enumeration. The following are the values available in this enumeration.

DockStyle DescriptionBottom The control’s bottom edge is docked to the bottom edge of its containing control.

FillAll the edges of the control are docked to all the edges of its containing control and is sized appropriately.

Left The control’s left edge is docked to the left edge of its containing control.Right The control’s right edge is docked to the right edge of its containing control.None The control is not docked.Top The control’s top edge is docked to the top edge of its containing control.

System.Windows.Forms.DockStyle Enumeration Values

Let’s try docking a button control into different edges of the form.

To dock a control, select the control to dock and go to Properties Window.

Page 128: Visual Programming

Find the Dock property and then click the drop down button. You will be presented with a small window with multiple buttons specifying where to dock the control.

The center square means that you will use the DockStyle.Fill value for the Dock property. The following screenshots shows the effect of docking the control to different edges.

Bottom

Page 129: Visual Programming

Top

Left

Right

Page 130: Visual Programming

Fill

If you have multiple controls and use the same docking values, then they will be placed beside or above each other.

Using the TabIndex Property You can cycle the focus of each control by pressing the tab key on the keyboard.

Each control has a TabIndex property which indicates the order each control will get focus when the tab key is pressed. It is important to monitor the TabIndex of each control and make sure that they are in sequence depending on the layout of the control. Consider a form with four text boxes.

Page 131: Visual Programming

Suppose that their TabIndex properties are not in sequence such as this.

TextBox TabIndextxtFirstName 1txtLastName 4txtGender 3txtAge 2

When you run the program, the focus will be on the control who has the lowest tab index. So therefore, the focused control will be txtFirstName. If you press tab, the focus will go to the control which has the next TabIndex. Therefore, txtAge will receive the focus. A good user experience makes use of TabIndex property. We want the receiving of focus for each control to be in the right sequence so user will not get irritated and find where the focus went. Determining the right sequence depends on the position of the controls. Since the textboxes on the form above are placed in a vertical manner (from top to bottom), the first TabIndex must be in the top textbox followed by the next below, and the bottom textbox having the highest tab index.

Please note that you can also use the TabIndex property on other controls such as a button. Suppose that you are through filling the fields in a form, pressing tab while you are in the last textbox will bring you to the accept button. You can do this by giving the button a TabIndex which is higher than the last text box. TabIndex property is useless on controls that cannot receive focus such as a Label control.

Adding Menus to Your Form Menu bars can be seen in almost every application out there. Menus are used to

contain different commands that the user can use. You can add menu bars to a form by using the MenuStrip control (System.Windows.Forms.MenuStrip). The MenuStrip is the container of the different menus. To add a menu bar to your form, drag a MenuStrip control from the Toolbox. It is located in the Menus & Toolbars Section.

Page 132: Visual Programming

You can also see the MenuStrip control in a section located at the bottom of the Designer. Located here are some non-visual components such as a Timer control and many more.

The MenuStrip control has the following useful properties.

Property Description

Dock Determines which location to dock the menu bar. The default is Top.

GripStyle Allows you to show the grip which is used to repositions items in the menu strip.

Items A collection of top-level menus.

Stretch Specifies whether the MenuStrip stretches from end to end in its container.

Figure 1 – MenuStrip Properties

Adding Standard Menus

Visual Studio offers you a way to automatically add standard items to the MenuStrip control. To do this, open the smart tag, which can be done by pressing the arrow button at the upper right side of the MenuStrip.

Page 133: Visual Programming

Then choose Insert Standard Items.

Visual Studio will fill the MenuStrip with standard menus such as Creating New files, Saving Files, Loading and many more.

Page 134: Visual Programming

Adding Your Own Menus

The standard menus might not suit what you specifically need. We can create our own custom menu bar using Visual Studio’s tools. You can either undo the placement of the standard menu by hitting Ctrl+Z or you can simply delete the MenuStrip and add a new one. To add a menu item, click the box labeled “Type Here” and type the name of the menu.

You will notice that as you type, another box will appear beside and below it so you can add more items. As an example, type File, Edit, and Help in the MenuStrip.

To add submenus, click a menu item it will open up a container for all its submenus. You will also see a box that will allow you to insert sub menus.

Page 135: Visual Programming

If you want to add a separator, type the - character.

You can even create submenus of submenus. You can nest and nest menus if you want to. A submenu which contains another submenu can be identified by the arrow at its right side.

Page 136: Visual Programming

Each text menu item you add is represented by ToolStripMenuItem. The separator is represented by ToolStripSeparator. The ToolStripSeparator is only used to separate related menus. Each ToolStripMenuItem is added to the MenuStrip‘s Item property and each submenu is added to the ToolStripMenuItem‘s DropDownItems property. Visual Studio automatically adds a name to each ToolStripMenuItem control which is based on the text you specified. Let’s discuss the properties of the ToolStripMenuItem.

Property Description

Checked Tells whether the item is checked.

CheckOnClick Tells whether an item will be checked or unchecked when it is clicked.

CheckState Tells whether the item is checked or unchecked.

DropDownItems A collection of submenus of the current item.

Enabled Enables of disables this item.

Image An optional image or icon that is shown at the left of the label.

ShortcutKeys The shortcut keys associated with the ToolStripMenuItem.

ShowShortcutKeys Tells whether the shortcut keys for an item is shown in the menu.

Text The text or label of the menu item.

ToolTipText The text inside the tool tip that appears when you hover your mouse on the

Page 137: Visual Programming

Property Description

menu item.

Figure 2 – ToolStripMenuItem Properties

Checking and Unchecking Menu Items

The CheckOnClick property allows a menu item to be checked or unchecked. For example, you can have a menu that shows a list of windows that will be shown. You can turn their CheckOnClick properties to true. When a menu item is checked, you will see a check in its left side.

You can use the Checked or CheckState property of the menu item to tell whether it is checked or unchecked.

Adding Shortcut Keys to a Menu Item

You can add shortcut keys to a menu item. The easiest one is by using the & (ampersand) character when typing the name of the menu item.

Page 138: Visual Programming

The letter following the & character will be considered as the shorcut key. For example, &Save will have S as the shortcut key and E&xit will have the X as the shortcut key. At the designer, the shortcut key will be underlined. The underline will not be shown during runtime unless you hit the Alt key. Using this type of shortcut key requires the use of the Alt key. To activate a menu item, you hit the Alt + Shortcut Key. For example, if the shortcut Key of the File menu is F, then you use Alt + F combination to activate the menu item.

If you want more complex shortcut combinations, then we have to use the ShortcutKeys property. Select a menu item and then go to the Properties Window and find the ShortcutKeys property. Click the drop down arrow to show you a small window that allows you to choose the shortcut keys for the current menu item.

Once you specified a shortcut combination, it will now appear beside the label of a menu item provided that the ShowShortcutKeys property of the menu item is set to True.

Page 139: Visual Programming

Adding Icons to Menu Items

You can add images or icons at the left side of a menu item as seen in the standard menus.

We use the Image property to do just that. Click the drop down button of the Image property in the Property Window. Choose which resource to use and then browse for the appropriate image. If the image is too large, then it will automatically be scaled based on the value of the ImageScaling property.

Page 140: Visual Programming

Adding Functionality to the Menu Items

Menu items have the Click event which occurs when the menu item is clicked. We can handle this event to give functionality to menu items. To add a Click event to a menu item, in the Designer, double click the menu item and Visual Studio will automatically create an event handler for you. For menu items that has CheckOnClick properties set to true, you can handle the CheckedChange or CheckStateChange events. As an example create another form and create a menu as seen below.

Double click the Exit menu item. Visual Studio will create an event handler for its Click event. Add the following code.

private void exitToolStripMenuItem_Click(object sender, EventArgs e){ Application.Exit();}

The static method Exit of the Application class simply closes the application.

Creating Toolbars A toolbar contains buttons and other components that serve as menu commands to

the user. Like the menu, toolbars are also seen in numerous famous applications such as the Microsoft Office 2003 products. Below shows the toolbar seen in the Microsoft Word 2003 interface.

Page 141: Visual Programming

Figure 1

ToolStrip Control

We used a ToolStrip control (System.Windows.Forms.ToolStrip) to contain the buttons or components of a toolbar. You can move a ToolStrip using the move handles represented by vertical dots to it’s left side provided that they are contained inside the ToolStripContainer control as we will see later. Below shows the important properties of the ToolStrip control.

Property Description

CanOverflowSpecifies whether the items that can’t fit inside the ToolStrip will be placed in a separate hidden area accessible via a drop-down button.

GripStyle Specifies whether the ToolStrip move handle is visible or hidden.

Items Contains the items that belong to the ToolStrip.

LayoutStyle Specifies how the items will be displayed.

ShowItemToolTips Specifies whether each items will show a tool tip.

Stretch Specifies the Orientation of the ToolStripPanel.

Figure 2 – ToolStrip Properties

Adding Standard Items to Toolbar

Before we create our own customized toolbar, let’s see how VS/VCE can automatically create standard items for use such as the Save, Open, Copy, and Paste buttons. Create a new Windows Forms Application and name it ToolBarDemo. From the Menus & Toolbars section of the Toolbar, drag a ToolStrip control to the form. You form should now look like this.

Page 142: Visual Programming

Click the small square with an arrow located to the top right side of the ToolStrip to reveal a small window.

Click the “Insert Standard Items” and VS/VCE will create standard buttons as seen below.

Page 143: Visual Programming

ToolStrip Items

The Items property will hold the items that is contained by the ToolStrip. There are multiple kinds of items that can be placed inside a ToolStrip and they all inherit from the ToolStripItem class.

ToolStripItem Description

ToolStripButtonAn item that represents a button. You can click this item to perform different actions.

ToolStripLabelAn item that represents a label used to show uneditable texts. It can also display an image instead of text.

ToolStripSplitButtonAn item that represents a button with a drop down arrow beside it. Clicking the drop down arrow shows a drop down menu that you can click. The button itself has its own functionality when clicked.

ToolStripDropDownButtonSimilar to the ToolStripSplitButton, this one also shows a button with a drop down arrow, but the button is now represented with an image that when clicked, opens up the drop down menu.

ToolStripComboBoxAn item that represents a combo box that shows a drop-down list of items that you can choose.

ToolStripProgressBar Adds a progress bar to your toolbar.

ToolStripSeparator Adds a horizontal or vertical divider between ToolStrip items.

Page 144: Visual Programming

ToolStripItem Description

ToolStripTextBoxA item that represents a text box. You can type a text in this item that will be used for processing.

Figure 3 – ToolStrip Items

The following section shows you how to create and use each of these ToolStrip items.

The ToolStripButton

The ToolStripButton control is the most basic component you see in a toolbar. You click a ToolStripButton control and it will execute its Click event just like an ordinary button. Delete the previous ToolStrip with standard menus and add a new ToolStrip control. If you select the ToolStrip, you will see an icon with a drop-down button beside it. Clicking it will show you a list of ToolStrip items you can add.

Choose the Button to add a ToolStripButton control to the ToolStrip.

Page 145: Visual Programming

The button uses a default icon. If you wan’t to change it, then you can use the Image property of the ToolStripButton in the Properties Window and then browse for the desired image. In the Designer, double click the created ToolStripButton to generate an event handler for its Click event. Add the following code inside the event handler.

MessageBox.Show("Button was clicked!");

The code above simply shows a message when you click the button in the ToolStrip. In a more realistic scenario, you will add codes that perform specific tasks such as changing the font style of a font in a text box.

The ToolStripLabel

The ToolStripLabel control allows you to add an uneditable text that can be used to describe other items. It also allows you to add an optional image beside the label. To add a ToolStripLabel, you click the new item icon in the ToolStrip and choose Label from the list.

Page 146: Visual Programming

When a new ToolStripLabel has been added, you can then use the Text property to change the text of the label.

You can also add an image by using the Image property. You can go to the Properties Window and click the button beside the Image property. You can then browse an image to be displayed beside the label.

Page 147: Visual Programming

The ToolStripSplitButton

The ToolStripSplitButton control represents a button that can be clicked. Additionally, it has a drop-down button beside it that when clicked, shows a drop-down menu related to the functionality of the button. One example of this control is the Add New Item button in the Toolbar of Visual Studio.

When you click the actual button, it shows the Add New Item Window instead of showing the list of menus. To add a ToolStripSplitButton control, click the new item icon in the ToolStrip and choose SplitButton.

Page 148: Visual Programming

When the ToolStripSplitButton is added, you can click its drop down button to add menu items by typing each one in.

The button and the menu items can react to their own Click events. Note that the button and each menu items’ Click event handler are separate from each other. Like the ToolStripButton control, you can also change the icon of the ToolStripSplitButton control using the Image property.

The ToolStripDropDownButton

The ToolStripDropDownButton is similar to the ToolStripSplitButton in that it also shows a drop-down menu when clicked. The only difference is that the actual button is simply an image

Page 149: Visual Programming

that when clicked, shows the menu as if you clicked the drop-down button. Therefore, the button’s purpose is just to open the hidden drop-down menu. Like the other ToolStripItems, you can create a ToolStripDropDownButton by clicking the new item icon in the ToolStrip and by choosing the DropDownButton.

Adding menu items is similar to the ToolStripSplitButton control. You simply type in the menu items that you want to add to the drop-down menu. Like the ToolStripButton control, you can also change the icon of the ToolStripDropDownButton control using the Image property.

The ToolStripComboBox

The ToolStripComboBox allows you to embed a combo box to your ToolStrip. It’s just like an ordinary ComboBox control. You add items using the Items property and you react to SelectedIndexChanged event.

Page 150: Visual Programming

The following shows a ToolStripComboBox with some items added to it.

Note that the default event of the ToolStripComboBox is the Click event so you need to go to the Events section of the Properties Window and find the SelectedIndexChanged event if you want to add an event handler to it.

The ToolStripTextBox

The ToolStripTextBox allows you to add a text box in the ToolStrip. The ToolStripTextBox is similar to an ordinary TextBox control and the most imporant property is the Text and it reacts to the TextChanged event.

Page 151: Visual Programming

Note that the default event of the ToolStripTextBox is the Click event so you need to go to the Events section of the Properties Window and find the TextChanged event if you want to add an event handler to it.

The ToolStripSeparator

The ToolStripSeparator control has only one purpose, to separate related ToolStrip items.

As you can see above, the ToolStripSeparator divides the ToolStrip into groups.

Page 152: Visual Programming

The ToolStripProgressBar

The ToolStripProgressBar is used to show the progress of a certain process such as saving, copying, deleting, or any task that may require the user to wait. It gives the user a hint on the progress of a certain process. Without it, the user may think that the program is stuck or is not responding properly.

The most important property for the ToolStripProgressBar is the Value and Step property. The Value property specifies the current progress of the progress bar. The Step property specifies how much to increment the Value when calling the PerformStep() method. As a simple example, change the Step property to 1 and add a Timer control from the Components section of the Toolbar to the form. Change the Enabled property of the Timer to True and double click it to generate an event handler for its Tick event. Add the following code inside the event handler.

toolStripProgressBar1.PerformStep();

This performs the PerformStep() method for every 100 milliseconds (as specified by the Interval of the Timer) and increases the value of the ToolStripProgressBar by 1 (as we specified in the Step property). Run the program and watch as the progress bar gradually fills.

Page 153: Visual Programming

Adding ToolTips to ToolStrip Items

Each item has a ToolTipText property that specifies the tool tip to show when you hover you mouse to an item. Please note that the ShowItemToolTips property of the ToolStrip must be set to True for the tool tips to show.

Using the CanOverflow and Overflow Properties

So what will happen if the toolbar has too many items that it won’t fit the space provided for the ToolStrip? By default, the CanOverflow property of the ToolStrip is set to True. This all the

Page 154: Visual Programming

items that are out of the width or height of the ToolStrip. You can then access them using a drop-down button as seen below.

You can also set the Overflow property of a ToolStripItem to Always. This puts an item to the hidden menu even if the ToolStrip still has lots of space.

The ToolStripContainer Control The ToolStripContainer control (System.Windows.Forms.ToolStripContainer)

serves as a container for toolbars. With this control, you can arrange and change the positions of the toolbars inside this container. The ToolStripContainer is composed of ToolStripPanels which

Page 155: Visual Programming

is the actual area where you place the ToolStrips. By default, there are four panels visible to each side of the ToolStripContainer.

Figure 1

The following are some of the properties of the ToolStripContainer control.

Property DescriptionBottomToolStripPanel Gets the bottom ToolStripPanel of this control.BottomToolStripPanelVisible Specifies whether the bottom ToolStripPanel is visible.ContentPanel Gets the center panel of this control.LeftToolStripPanel Gets the left ToolStripPanel of this control.LeftToolStripPanelVisible Specifies whether the bottom ToolStripPanel is visible.RightToolStripPanel Gets the right ToolStripPanel of this control.RightToolStripPanelVisible Specifies whether the right ToolStripPanel is visible.TopToolStripPanel Gets the top ToolStripPanel of this control.TopToolStripPanelVisible Specifies whether the top ToolStripPanel is visible.

Figure 2 – ToolStripContainer Properties

Let’s look at the ToolStripContainer in action. Create a new Windows Forms Application and name it ToolStripContainerDemo. Add a ToolStripContainer from the Menus & Toolbars section of the Toolbox to the form. Change the Dock property of the ToolStripContainer to Fill.

Page 156: Visual Programming

By default, only the top ToolStripPanel is shown. You can now add multiple ToolStrips to this panel by dragging them from the toolbox to this area. The arrows on the sides allows you to create new panels. For example, by clicking the arrow in the left side of the container, a new ToolStripPanel will be created and will be available as a container for ToolStrips.

Let’s add two ToolStrips to the top panel. Also add three ToolStripButtons to each of them.

Page 157: Visual Programming

Notice that as you add new ToolStrips, the new one is placed below or next to the previous one. The size of the panel also changes automatically to accomodate the ToolStrips. Run the program to see the toolbars. By clicking and draging the move handles of each ToolStrip, you can arrange or change their position and orientation. For example, you can drag the second ToolStrip up and place it next to the first one.

Remember that we added a ToolStripPanel to the left side of the ToolStripContainer. This is invisible at runtime if it is empty. But you can drag a ToolStrip to it as seen below.

Page 158: Visual Programming

Back to the Designer. If you wan’t the ToolStrip to occupy the whole row or column, then you can set it’s Stretch property to True.

If you don’t want the ToolStrip to be moved, then you can set its GripStyle property to Hidden.

Page 159: Visual Programming

You can also disable the ToolStripPanels if you won’t be needing them. To do this, select the ToolStripContainer. It may be hard to do this manually so you may go to the Properties Window and use the combo box located to the top of it. Find the toolStripContainer1 and select it.

Click the square icon to the upper right side to open up a window. Uncheck the panels that you want to disable.

Dialogs

Page 160: Visual Programming

Dialogs are windows that has certain specific function such as saving or opening a file, choosing a color, or printing a document. The .NET frame work offeres the dialog controls which allows you to call dialogs to do specific task. The dialogs can be customized using the properties of those controls.

Dialog for Picking Colors

Dialog for Browsing Folders

Page 161: Visual Programming

Dialog for Choosing Font Styles

Dialog for Saving a File

Page 162: Visual Programming

Dialog for Openning a File

Although you can construct your own dialogs, using this predefined dialogs makes your application more standardized as a Windows application as almost all application in Windows uses these dialogs. Note that dialogs’ appearance may look different on other versions of Windows such as Windows XP. The screenshots above are dialogs of Windows 7 operating system.

The ColorDialog Control The ColorDialog (System.Windows.Forms.ColorDialog) is used when you want to

pick different colors. For example, when you want to pick for a color of the font or a background color for the form, you can use the ColorDialog control.

Page 163: Visual Programming

The following are some of the useful properties of the ColorDialog control.

Properties DescriptionAllowFullOpen Specifies whether the user can choose custom colors.Color The color that the user selected.CustomColors A collection of custom colors picked by the user.FullOpen Specifies whether the part used to pick custom colors are automatically open.

The window of the initially composed of predifined color pallettes. You can click the Define Custom Colors button to reveal a more colors where you can pick every color you can think of. You can even provide the Hue, Saturation, Luminance values or RGB values. The main window allows you to choose colors while the right slider adjusts the brightness of the color. You can click the Add Custom Colors button to put the selected color to the Custom Colors pallete so you can reuse it later.

The following example, demonstrates the use of the ColorDialog. Create a similar form shown below.

Page 164: Visual Programming

Drag a ColorDialog control to the form. It will not be visible to the form but you can find it a the bottom section of the Designer.

Page 165: Visual Programming

To change properties of the ColorDialog control, click it in the designer and proceed to Properties Window.

Double click the button to create an event handler for its Click event. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e){ DialogResult result = colorDialog1.ShowDialog();

if (result == DialogResult.OK) { this.BackColor = colorDialog1.Color; }}

The first line of code calls the ColorDialog‘s ShowDialog static method. This method shows up the color dialog where the user can pick a color. This method returns a System.Windows.Forms.DialogResult value which indicates whether the user clicked the OK or the Cancel button of the Dialog. If the user clicked a color and pressed the OK button, the dialog closes and the color the user picked is stored in the Color property of the control. We test the value of the result to determine if the user clicks the OK button.  If so, we changed the background color of the form to the color the user picked using the value of the Color property.

Run the program and click the button. The Color dialog will open up. Select a color and click OK. Watch as the color of the form changes to the color you have picked.

The FontDialog Control

Page 166: Visual Programming

The FontDialog control (System.Windows.Forms.FontDialog) is a handy control for selecting different kinds of font and font-related properties.

Using the FontDialog, you can change the font type, style, size, color, add effects and specify character sets for the font. You can also preview the actual font. The following are some of the useful properties of the FontDia control.

Properties DescriptionColor The selected color of the user.Font The resulting font constructed using the font dialog.MaxSize The maximum size the dialog can provide.MinSize The minimum size the dialog can provide.ShowApply Indicates whether to show the Apply button.ShowColor Indicates whether to show the Color option.ShowEffects Indicates whether to show the Effects option.

Note that the FontDialog hides the option to chose color by default. To allow the user to choose a color, set the value of the ShowColor property to true. You can then access the selected color via the Color property. The ShowApply property allows you to show the Apply button on the FontDialog. You can then handle the Apply event to apply the changes to the target font while not closing the dialog itself.

Let’s look at a simple example of using the FontDialog control. Create a form similar to the form show below.

Page 167: Visual Programming

We will be changing the font of the text box depending on the constructed font using the FontDialog control. Drag a FontDialog control to the form. Since the FontDialog control is not a visual control, it will be located at the bottom portion of the Designer. Double click the button and use the code below for the event handler.

private void button1_Click(object sender, EventArgs e){ DialogResult result = fontDialog1.ShowDialog();

if (result == DialogResult.OK) { textBox1.Font = fontDialog1.Font; }}

We first called the ShowDialog static method of the FontDialog control to show the actual dialog to the user. The user can now pick the different font properties and click OK. We check if the user presses the OK button by testing the value returned by the ShowDialog mehtod. If the user presses OK then we change the font of the textbox to the one specified by the user.

Page 168: Visual Programming

Run the program and type any text inside the text box. Click the button to open up the Font Dialog and then choose the desired font. Click OK and the font of the text box will change.

The FolderBrowserDialog Control The FolderBrowserDialog contrl (System.Windows.Forms.FolderBrowserDialog)

allows you to browse for a directory in your system. The control uses a tree view to show all the folders. The Browser shows the Desktop (by default) as the top level root folder and below it are its content. You can click the arrows or each folder to show other folders/subdirectories inside it. You can also create a new folder inside the selected folder or directory.

Page 169: Visual Programming

The following are some of the useful properties of the FolderBrowserDialog control.

Property Description

DescriptionAllows you to add a descriptive text above the tree view of the FolderBrowserDialog.

RootFolderGets or sets the folder that the FolderBrowserDialog will consider as the root or the top level folder.

SelectedPath The folder or path that the user has selected.ShowNewFolderButton Shows or hides the Make New Folder button.

The Description property allows you to add a description right above the tree view of the dialog.

If you don’t want the desktop as the top level root folder, then you can use the RootFolder property.  In the properties window, find the RootFolder property and press the drop down button beside it. You will be shown with predefined paths that you can choose.

Page 170: Visual Programming

You can retrieve the selected folder or path using the SelectedPath property. The path is returned as a string.

We will now create an example application to show the use FolderBrowserDialog control. Our example program will allow the user to choose a directory, then it will be displayed in a text box. The contents of the directory will then be listed using a list box. Create a new form similar to the one below. which contains a button, text box, and a list box control.

Page 171: Visual Programming

Add the FolderBrowserDialog from the Dialogs category of the Toolbox. The control will be located below the bottom portion of the Designer. Double click the Browse button and use the code below for the event handler.

private void button1_Click(object sender, EventArgs e){ DialogResult result = folderBrowserDialog1.ShowDialog();

if (result == DialogResult.OK) { //Show the path using the text box textBox1.Text = folderBrowserDialog1.SelectedPath;

//Obtain information about the path DirectoryInfo selectedPath = new DirectoryInfo(textBox1.Text);

//Clear the list box first listBox1.Items.Clear();

//Check if there are directories then add a label if (selectedPath.GetDirectories().Length > 0) listBox1.Items.Add("== Directories ==");

//Show all the directories using the ListBox control foreach (DirectoryInfo dir in selectedPath.GetDirectories()) { //Show only the name of the directory listBox1.Items.Add(dir.Name); }

//Check if there are files then add a label if (selectedPath.GetFiles().Length > 0) listBox1.Items.Add("== Files ==");

//Show all the directories using the ListBox control foreach (FileInfo file in selectedPath.GetFiles()) { listBox1.Items.Add(file.Name); } }}

Please note that we also need to import the System.IO namespace above the code.

using System.IO;

First, we called the FolderBrowserDialog using the ShowDialog method. The user can now pick a folder and press OK. We need to test if the user pressed the OK button. This can be determined using the value returned by the ShowDialog method. If the user presses the OK button, we display the selected path in the text box.

DirectoryInfo selectedPath = new DirectoryInfo(textBox1.Text);

Page 172: Visual Programming

This line creates a new DirectoryInfo object using the path selected by the user. A DirectoryInfo object is contained in the System.IO namespace. It contains properties that describes a directory such as the full path of the directory, and its contents. We clear the contents of the list box in case there are some previously added items exists.

//Check if there are directories then add a labelif (selectedPath.GetDirectories().Length > 0) listBox1.Items.Add("== Directories ==");

//Show all the directories using the ListBox controlforeach (DirectoryInfo dir in selectedPath.GetDirectories()){ //Show only the name of the directory listBox1.Items.Add(dir.Name);}

We then check if there are subdirectories inside the current folder using the Length property of the DirectoryInfo[] value returned by calling the GetDirectories method. If so, we create a label and add it to our list box. We enumerate all the subdirectories inside the current folder using the GetDirectories method and a foreach loop. loop. We add the name of each subdirectory to the list box.

//Check if there are files then add a labelif (selectedPath.GetFiles().Length > 0) listBox1.Items.Add("== Files ==");

//Show all the directories using the ListBox controlforeach (FileInfo file in selectedPath.GetFiles()){ listBox1.Items.Add(file.Name);}

We used the same technique for enlisting all the files inside the selected folder. But this time, we use the GetFiles method and FileInfo objects. The FileInfo object contains information about a specified file.

Now execute the program and select a folder. Press OK and look as the program shows you the directories and folders contained inside the selected folder.

The OpenFileDialog Control The OpenFileDialog control (System.Windows.Forms.OpenFileDialog) allows you

to open and read file contents such as texts from text files. The dialog allows you to browse your file system and pick a directory. You can type the name of the file that exist in the current directory or you can type the whole path of a file or directory in the File Name text box located at the bottom of the dialog.

Page 173: Visual Programming

The following table shows some useful properties of the OpenFileDialog control.

Property Description

AddExtentionSpecifies whether to automatically add an extention when the user omits the extention of the file he or she chooses.

CheckFileExists Specifies whether to initiate a warning if the user types a file that does not exist.

CheckPathExists Specifies whether to initiate a warning if the user types a path that does not exist.

DefaultExt The default extention to add when the user does not indicate a file extention.

FileNameThe file selected by the user. This can also be the default selected file when the dialog shows up.

FileNames A collection of files that the user picked.

FilterAllows you to add a filter which are a special string indicating which types or files are only allowed to be openned by the user.

FilterIndexIf multiple filters are present, this indicates which filter shows as the default starting with index 1.

InitialDirectory The initial directory that the OpenFileDialog will show.

Page 174: Visual Programming

Property Description

Multiselect Tells whether the user can select multiple files.

Title The title of the dialog.

The AddExtention property automatically adds an extention when the user does not indicate the file extention of the file name. The extension to add is specified by the DefaultExt property. The CheckFileExists and CheckPathExists methods are recommended to be set to true so the dialog will issue a warning message if it cannot find the specified file or directory. The InitialDirectory property specifies the initial directory that the dialog will show when you open it up. The Title property is the title of the dialog located at the title bar. The FileName property is the selected file selected or specified by the user. You can allow a user to select multiple files by setting the Multiselect property to true. You can then use the FileNames property to get the collection of selected file names.

Filtering Files

We can filter the files to be shown by their file types. We use the Filter property which accepts a string containing a special pattern. For example, we can set the dialog to only show text files by filtering the results to only files with .txt file extentions. The Filter property requires a special pattern.

Description1|FilterPattern1|Description2|FilterPattern2|...DescriptionN|FilterPatternN

We first start with a description telling about the type of file. We then follow it with a vertical bar (|) followed by the filter pattern. For example, the following pattern only shows the text files.

Text Files|*.txt

The description here is Text Files and the pattern is *.txt. The * character is a wild card character which means any names. The .txt portion specifies the specific file extention. The filter pattern says any file with a file extention of .txt. You can also use the wildcard characters for many other purpose. For example, m*.txt is the pattern for all the text files that start with letter m. *r.txt is the pattern for all the text files that ends with letter r, *.* is the pattern for all kinds of files, *.t* is the pattern for all files that have a file extention that starts with letter t.

You can specify multiple filters. For example, the following pattern adds multiple filters.

Text Files|*.txt|Bitmap Files|*.bmp|All Files|*.*

You can select a filter using a combo box next to the file name text box of the dialog.

Page 175: Visual Programming

You can group a set of file extensions for a single description. For example, image files consist of different file extensions such as bmp, jpeg, or png. You simply separate the file extentions using semicolons.

Image Files|*.bmp;*.jpeg;*.png;*.gif

When you select this filter, then all of the files that matches one of the filter patterns will be shown.

OpenFileDialog Control Example

We will now create an example application that uses the basic capabilities of the OpenFileDialog control. The application will allow a user to browse for a text file and view its contents using a multiline text box. Please note that we need to import the System.IO namespace in our code.

using System.IO;

Page 176: Visual Programming

Create a form similar to the one below. Use a multiline text box by setting the Multiline property to true. Set the Scrollbars property of the text box to both and the WordWrap property to false (optional). Drag an OpenFileDialog control from the toolbox to the form.

Double click the button to create an event handler for its Click event. Again, import the System.IO namespace first at the top of the code. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e){ //Filter to only text files openFileDialog1.Filter = "Text Files|*.txt"; //No initial file selected openFileDialog1.FileName = String.Empty;

//Open file dialog and store the returned value DialogResult result = openFileDialog1.ShowDialog();

//If Open Button was pressed if (result == DialogResult.OK) { //Create a stream which points to the file Stream fs = openFileDialog1.OpenFile(); //Create a reader using the stream StreamReader reader = new StreamReader(fs); //Read Contents textBox1.Text = reader.ReadToEnd(); //Close the reader and the stream reader.Close(); }}

The first line adds a filter using the Filter property. We specified in the pattern to only allow the user to open text files. The second one assigns an empty string to the FileName so there is no file

Page 177: Visual Programming

selected by default. We then open the OpenFileDialog using its ShowMethod property which returns a DialogResult value. The user can now choose a text file by browsing the system. When the user presses the Open button while a valid file is selected, then the method ShowDialog will return DialogResult.OK. We tested this using an if statement. We used the OpenFile method of the OpenFileDialog control and store it in a Stream object. The Stream object points to the selected file and we use this object to create a StreamReader object which is used to read the stream(the file). We used the ReadToEnd method of the StreamReader object to read all the contents of the file and return the result as tring. We then place the result inside the text box.

Execute the application and click the button. Browse for a text file and click Open. If the file the user types cannot be found, then an error will show up if the CheckFileExists and CheckPathExists properties are set to true. If the file is valid and you press Open, then the contents of the file will be shown in the text box.

The SaveFileDialog Control The SaveFileDialog control (System.Windows.Forms.SaveFileDialog) allows you to

save or write data to a specified file. The dialog allows you to browse your file system and pick a directory, then type a filename you want to be the name of the file that will contain the data to be written. You can type the name of the file that exist in the current directory and the dialog can prompt you if you want to overwrite it. You can also type the whole path of a file or directory in the File Name text box located at the bottom of the dialog.

The following table shows some useful properties of the SaveFileDialog control.

Page 178: Visual Programming

Property Description

AddExtentionSpecifies whether to automatically add an extention when the user does not specify a file extension.

CheckFileExists Specifies whether to initiate a warning if the user types a file that does not exist.

CheckPathExists Specifies whether to initiate a warning if the user types a path that does not exist.

DefaultExt The default extention to add when the user does not indicate a file extention.

FileNameThe file selected by the user. This can also be the default selected file when the dialog shows up.

FilterAllows you to add a filter which are a special string indicating which types or files are only allowed to be openned by the user.

FilterIndexIf multiple filters are present, this indicates which filter shows as the default starting with index 1.

InitialDirectory The initial directory that the OpenFileDialog will show.

OverwritePromptSpecifies whether the dialog will prompt you to overwrite a file when an existing file is already found.

RestoreDirectory Specifies whether to restore to default directory when the dialog closes.

Title The title of the dialog.

The AddExtention property automatically adds an extention when the user does not indicate the file extention of the file name. The extension to add is specified by the DefaultExt property. The CheckFileExists and CheckPathExists methods are recommended to be set to true so the dialog will issue a warning message if it cannot find the specified file or directory. The InitialDirectory property specifies the initial directory that the dialog will show when you open it up. The Title property is the title of the dialog located at the title bar. The FileName property is the Filename specified by the user.

Specifying File Types

We can specify the file types that the file will have.  We use the Filter property which accepts a string containing a special pattern. For example, we can set the dialog to only allow our file to be save as a text file with .txt file extentions. The Filter property requires a special pattern.

Description1|Extension1|Description2|Extention2|...DescriptionN|ExtentionN

Page 179: Visual Programming

We first start with a description telling about the type of file. We then follow it with a vertical bar (|) followed by the extension. For example, the following pattern allows you to save files as text files.

Text Files|.txt

The description here is Text Files and the extention is .txt. You can specify multiple extensions. For example, the following pattern allows you to save a file as a .txt, or .png.

Text Files|*.txt|Image|*.png

You can select the type that the file will be saved as using the combo box below the File Name text box.

SaveFileDialog Control Example

We will now create an example application that uses the basic capabilities of the SaveFileDialog control. The application will allow a user to type into a multiline text box and then save the text

Page 180: Visual Programming

into a text file using a specified file name and path. Please note that we need to import the System.IO namespace in our code.

using System.IO;

Create a form similar to the one below. Use a multiline text box by setting the Multiline property to true. Drag a SaveFileDialog control from the Dialogs category of the Toolbox to the form.

Double click the button to create an event handler for its Click event. Again, import the System.IO namespace first at the top of the code. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e){ //Specify the extensions allowed saveFileDialog1.Filter = "Text File|.txt"; //Empty the FileName text box of the dialog saveFileDialog1.FileName = String.Empty; //Set default extension as .txt saveFileDialog1.DefaultExt = ".txt";

//Open the dialog and determine which button was pressed DialogResult result = saveFileDialog1.ShowDialog();

//If the user presses the Save button if (result == DialogResult.OK) { //Create a file stream using the file name FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create); //Create a writer that will write to the stream StreamWriter writer = new StreamWriter(fs);

Page 181: Visual Programming

//Write the contents of the text box to the stream writer.Write(textBox1.Text); //Close the writer and the stream writer.Close(); }}

The first line specifies that we can only save our file as a text file with .txt extension. The second one assigns an empty string to the FileName so the File Name text box of the dialog will be initially empty (you can indicate a default filename though). We set the default extention to be .txt so if the user only types the name and forgot or do not include the extention, the dialog will automatically add the extention name in case no file type is selected. We then open the SaveFileDialog using its ShowMethod property which returns a DialogResult value. The user can now browse the directory where he/she wants to save the file. When the user presses the Save button, then the method ShowDialog will return DialogResult.OK. We tested this using an if statement. We created a FileStream object and set the file name and file mode. We then create a StreamWriter object and pass the FileStream object. We use the Write method of the writer to write the contents of the text box to the stream and save it to the file. Finally, we close the writer which also closes the file stream.

Execute the application and type anything inside the text box. Click the button and choose a directory. Then type a file name and hit Save. If a similar file exist, you may be prompted if the program should overwrite the file. Setting OverwritePrompt to false will automatically overwrite the file without prompting.

Dynamically Adding Controls Visual Studio offers you ways to design forms visually thanks to its Designer. You

can simply drag and drop controls, drag them to specified locations, change their properties, and attach events. But how can you add controls during runtime where the tools from Visual Studio are not accessible? You can do so by adding them programmatically. Whenever you place a control to the form, Visual Studio generates a code that creates the object representing the control, initialize the properties specified and attach event handlers specified in the Properties Window. You can see all the generated code using the generated Designer file of every form class you create as discussed in the Separating Design and Functionality lesson.

This time, you will do the same technique that Visual Studio do to create controls. You will be adding a control dynamically during runtime. To demonstrate how we can do this, let’s create an application that adds all the numbers typed by the user. The program will dynamically add labels and text boxes that will hold the numeric input. The number of inputs will be given by the user.

Create a new Windows Forms Application. Add a label, text box and a button as seen below. Change the name of text box to textBoxInput, and the button to buttonGenerate.

Page 182: Visual Programming

Go to Code Editor by pressing F7. Use the highlighted code below and put it inside the Form’s constructor right below the InitializeComponent method.

public Form1(){ InitializeComponent(); this.AutoSizeMode = AutoSizeMode.GrowAndShrink; this.AutoSize = true; this.Padding = new Padding(0, 0, 20, 20); this.StartPosition = FormStartPosition.CenterScreen;}

What we have done here is to demonstrate how we can manually specify values for the properties of a control, in this case, the form. The this keyword specifies the form because the code is inside the Form class. You can now see that these properties (which is normally set using Properties Window) can also be done in code. The first line of code specifies the AutoSizeMode property of the form to grow and shrink whenever neccessary to accomodate the controls that will be dynamically added. We then set the AutoSize property to true. We have done this so that the form will automatically resize when new controls are added or removed. We also added padding to the right and bottom of the form as specified by the third line. This is to add some space to the right and bottom of the form since autosize is activated. The StartPosition property of the form allows the form to initially show up in the center of the screen of your monitor.

Before we continue, add a private member for our form class that will accept a collection of TextBoxes.

private List<TextBox> inputTextBoxes;

This will hold all of our input boxes so we can reference each of them and get their individual values for addition.

Go to the Designer by pressing Shift + F7. Double click buttonGenerate to create an event handler for its Click event. Use the following code for the event handler.

private void buttonGenerate_Click(object sender, EventArgs e){ //Get the number of input text boxes to generate int inputNumber = Int32.Parse(textBoxInput.Text);

//Initialize list of input text boxes inputTextBoxes = new List<TextBox>();

//Generate labels and text boxes

Page 183: Visual Programming

for (int i = 1; i <= inputNumber; i++) { //Create a new label and text box Label labelInput = new Label(); TextBox textBoxNewInput = new TextBox();

//Initialize label's property labelInput.Text = "Input " + i; labelInput.Location = new Point(30, textBoxInput.Bottom + (i * 30)); labelInput.AutoSize = true;

//Initialize textBoxes Property textBoxNewInput.Location = new Point(labelInput.Width , labelInput.Top - 3);

//Add the newly created text box to the list of input text boxes inputTextBoxes.Add(textBoxNewInput);

//Add the labels and text box to the form this.Controls.Add(labelInput); this.Controls.Add(textBoxNewInput); }

//Create an Add button Button buttonAdd = new Button(); //Initialize Properties buttonAdd.Text = "Add"; //Make the button show up in the middle of the form and right below the last input box buttonAdd.Location = new Point(this.Width / 2 - buttonAdd.Width / 2, inputTextBoxes[inputTextBoxes.Count - 1].Bottom + 20); //Add an event handler to the button's click event buttonAdd.Click += new EventHandler(buttonAdd_Click);

//Add the button to the form this.Controls.Add(buttonAdd);

//Center the form to the screen this.CenterToScreen();}

Don’t worry if Visual Studio highlights an error in this code as it will be fixed later. The first thing we did is retrieve the value which indicates how many input boxes and labels to generate. We then initialize the inputTextBoxes variable to preparet it to hold the input boxes. We now enter a for loop which will repeat on generating new labels and text boxes depending on the number specified by the user. Inside the for loop, we created a new Label and TextBox instances. The following codes initializes/modifies the properties of the created controls.

labelInput.Text = "Input " + i;labelInput.Location = new Point(30, textBoxInput.Bottom + (i * 30));labelInput.AutoSize = true;

The first line assigns the new label with a text depending on the position of the index in the loop. The second line relocates the position of the new label. If we failed to do this, the label will show

Page 184: Visual Programming

up in its default location which is the top left portion of its container. If you are coding the Location and not using the Designer, you might find it hard to estimate the exact location you want your label to show. The Location property accepts a Point value so we created a new Point object using a constructor that accepts the X coordinate and the Y coordinate of the control. The first argument which is the X coordinate, was just an estimate location. The Y coordinate uses some simple math so that each control will added will have a distance relative to the bottom of the top text box (the text box that was used to determine the number of inputs). The expression simply says that the first generated text box will be 30 pixels from the bottom of textBoxInput, the next generated text box will be 60 pixels, the third will be 90 pixels and so on. The AutoSize property is then set to true because the default is false. As you can see, we did not set all the available properties of the Label control because each property has a default value so we can only concentrate on properties that we really want to change. Let’s proceed to the next code which determines the location of the generated input text box.

textBoxNewInput.Location = new Point(labelInput.Width , labelInput.Top - 3);

The Location property of the new text box was assigned with a Point object with an X coordinate equal to the width of its label pair. This makes the text box position right next to the label. The Y coordinate is the same with its label pair but we subtract 3 pixels so the center of the text box is aligned to the center of its label pair.

inputTextBoxes.Add(textBoxNewInput);

The above code adds the newley created text box to the TextBox collection that will be used later on. The following method shows how we can add the created controls to the form.

this.Controls.Add(labelInput);this.Controls.Add(textBoxNewInput);

Controls which serves as containers such as forms has a Controls property which contains all the controls that are inside it. We use its Add method and pass the individual controls to be added. Once they are added to the form, they will now be drawn to the screen once the form is initialized and is finished loading.

this.CenterToScreen();

This code recenters the form in the screen. Since the form’s size was changed when we added controls, this code is neccessary.

After all the input boxes are generated, we need to add the button that will add the values that the user will provide.

Button buttonAdd = new Button();;buttonAdd.Text = "Add";buttonAdd.Location = new Point(this.Width / 2 - buttonAdd.Width / 2, inputTextBoxes[inputTextBoxes.Count - 1].Bottom + 20);buttonAdd.Click += new EventHandler(buttonAdd_Click);this.Controls.Add(buttonAdd);

Page 185: Visual Programming

The first line creates the button. Then we specified the text of the button. The third line positions the button to the center of the form and right below the last added input text box. The expression for computing the X coordinate gets the location of the center of the form. Since the left side of the control is positioned to the center, we need to subtract half the width of the button to the calculated center to position it in the middle of the form’s center. We got the Y coordinate by getting the bottom of the last input text box in the inputTextBoxes collection. The last input text box was detemined by the index equal to the count of items in the collection subtracted by one.

The next line adds an event handler to its click event. If you did’nt copy the code and type this, right after type += , Visual Studio will allow you to press Tab twice to automatically generate an event handler for this event. The event handler for this event will be shown later. Right now, we can see that the event handlers name is buttonAdd_Click. The last code simply adds the button to the form.

Type this method which is the event handler for the Click event of the buttonAdd. If this was automatically generated by Visual Studio described by the technique above, then you will find a NotImplementedException inside it which you can simply delete and replace with the following code.

void buttonAdd_Click(object sender, EventArgs e){ int sum = 0;

foreach (TextBox inputBox in inputTextBoxes) { if (inputBox.Text == String.Empty) { MessageBox.Show("Plaese fill in all the text boxes.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { sum += Int32.Parse(inputBox.Text); } } MessageBox.Show("The Sum is " + sum);}

This is the code that executes when the button for adding is clicked. You have seen how this code was added as an event handler of the buttonAdd‘s click event. We created a variable that will hold the sum of all the values in each text box. Using a foreach loop, we retrieve each text box and access its content. There is a simple validation inside the loop which test if the text box is filled with a value or is empty. If it is empty, an error is shown and the method is terminated. If there is a valid number inside the text box, it is added to the value of sum. After looping through all the text boxes and adding each of their values to the sum, the result is then displayed.

Run the program and type 5 in the text box. Click generate and the program will create 5 text boxes.

Page 186: Visual Programming

Watch as the the form is recentered in the screen. Type some values in the text boxes and click the add button to show the sum.

You have now experienced the tedious process of manually creating controls without the help of the Designing tools of Visual Studio. This is not recommended when designing the initial layout of the form. You can use this technique when you wan to dynamically create controls depending on factors that changes such as an input from the user.

Mouse Events You can use several special events to react to certain mouse interactions to the control.

You have seen the Click event which occurs when the a control is clicked by the mouse (although pressing Enter while the control is selected also generates the Click event). As you will see, there are more advanced events that are specifically used for handling mouse interactions. Some of these events have a type MouseEventHandler delegate which has a parameter MouseEventArgs that contains details about the mouse operation. The following the Mouse events that you can use.

Event DescriptionMouseCaptureChanged Occurs when the control loses or gains mouse capture.MouseClick Occurs when the control is clicked by the mouse.MouseDoubleClick Occurs when the control is double clicked by the mouse.

MouseDownOccurs when the mouse pointer is over the control and a mouse button is pressed.

MouseEnter Occurs when the mouse pointer enters the control.MouseHover Occurs when the mouse pointer rests on the control.MouseLeave Occurs when the mouse pointer leaves the control.MouseMove Occurs when the mouse pointer is moved over the control.

Page 187: Visual Programming

Event Description

MouseUpOccurs when the mouse pointer is over the control and a mouse button is released.

MouseWheel Occurs when the mouse wheel moves while the control has focus.

Figure 1 – Mouse Events

Let’s now take a look at the capabilities of some of these events. Create a new Windows Forms Application and add a button in the middle of the form.

Let’s add an event handler for the button’s MouseEnter and MouseLeave events. What we would like to do is whenever the mouse enters the client area of the button, the button will be grow bigger, and when the mouse leaves, it will return to its original size.

Go to the Properties Window and click the Events button represented by a thunder icon. Then find the MouseEnter event and double click it to create an event handler for that event.

private void button1_MouseEnter(object sender, EventArgs e){ button1.Height += 30; button1.Width += 30; button1.Top -= 15; button1.Left -= 15;}

When the mouse enters the control, its height and width is increased by 30 pixels. When the button is resized, it stays in the same position so the button will not appear in the center. We moved the button 15 pixels to the top and left (half of 30) so when the button is resized, it will still be centered. We now need to reset the size and location of the button when the mouse leaves

Page 188: Visual Programming

the control. Go again to the properties window and find the MouseLeave event and double click it.

private void button1_MouseLeave(object sender, EventArgs e){ button1.Height -= 30; button1.Width -= 30; button1.Top += 15; button1.Left += 15;}

The event handler simply reverts the operation done by the MouseEnter event handler.

The MouseClick event is an enchanced version of the Click event. It allows you to determine some details about the click such as the location in the control where the mouse is clicked. Let’s add an event handler for the button’s MouseClick event. Again, go to the Properties Window and find the MouseClick in the events section and double click it. Use the following code to show the location of the click with respect to the top left corner of the control.

private void button1_MouseClick(object sender, MouseEventArgs e){ MessageBox.Show(String.Format("Clicked at point ({0}, {1})", e.X, e.Y));}

The event handler uses the MouseEventArgs object to access the X and Y properties which represents the X and Y coordinates of the point where the mouse was clicked. Now, when you click the button, a message box will appear showing the location of the click.

The MouseDown event is triggered when a button is pressed down while the mouse is over the control. The MouseUp event is the reversed and occurs when the pressed button is released. Let’ demonstrate this event. Add an event handler to the MouseDown event. Just so the MouseClick event handler will not interfere with this event, comment out or delete its content. Now use the following code for the MouseDown event handler.

private void button1_MouseDown(object sender, MouseEventArgs e){ if (e.Button == MouseButtons.Left) MessageBox.Show("Left Click"); else if (e.Button == MouseButtons.Right) MessageBox.Show("Right Click"); else MessageBox.Show("Middle Click");}

The event handler uses the MouseEventArgs object to access the Button property which contains the details of which mouse button was clicked. The MouseButton enumeration contains values Left, Right, and Middle to refer to the three mouse buttons.

You can handle the MouseWheel event to detect if the mouse wheel has been moved. The mouse wheel event is not available in the Properties Window so we need to access it in code. In the

Page 189: Visual Programming

form’s constructor, right below the InitializeComponent method, type the following code. The moment you type +=, press the tab key twice to generate an event handler for the MouseWheel event.

public Form1(){ InitializeComponent(); button1.MouseWheel += new MouseEventHandler(button1_MouseWheel);}

Use the following event handler for the MouseWheel event.

void button1_MouseWheel(object sender, MouseEventArgs e){ button1.Height += e.Delta / 60; button1.Width += e.Delta / 60; button1.Top -= e.Delta / 120; button1.Left -= e.Delta / 120;}

We used the Delta property of the MouseEventArgs class. The Delta represents the number of notches that were moved forward or backward. Each notch is equal to the WHEEL_DATA constant which is 120. We divide Delta by 60 so each notch of the mouse wheel moved will only increase the width and height by 2 pixels instead of 120. Moving the wheel forward yields a positive Delta value and moving it backwards yields a negative value. The last two lines are used to adjust the position of the button so it will always be centered. Instead of dividing by 60, we divide the Delta by 120 so every moved notch, the top and left of the button will move by 1 pixel. Run the program and while the button has the focus, move the wheel forward to increase the size of the button, and backwards to decrease its size.

Keyboard Events When you want to handle events when pressing keys in the keyboard, you can

handle the KeyPress, KeyDown, and KeyUp events. The KeyDown event occurs when a keyboard key is pressed down and the KeyUp event occurs after you release the pressed key. The KeyPress event triggers when a complete keypress is made(pressing then releasing the key). The following example adds a KeyPress event to the form and whenever a key is pressed in the keyboard, it is added to the text of a label. Create a new Windows Forms Application and name it KeyBoardEvents then add a Label control.

Page 190: Visual Programming

Remove the text of the Label. Select the form and in the Properties Window, find the KeyPress event and double click it to create an event handler. Use the code inside the Form1_KeyPress event handler of the code below.

1: using System; 2: using System.Windows.Forms; 3: 4: namespace KeyBoardEvents 5: { 6: public partial class Form1 : Form 7: { 8: //Variable to count letters for simple word wrap 9: private int charCount = 0; 10: 11: public Form1() 12: { 13: InitializeComponent(); 14: } 15: 16: private void Form1_KeyPress(object sender, KeyPressEventArgs e) 17: { 18: charCount++; 19: 20: //Go to next line after the line's 30th character 21: if (charCount > 30) 22: { 23: label1.Text += "\r\n"; 24: charCount = 0; 25: } 26: else 27: { 28: //Append the pressed keyboard key to the label using KeyChar property 29: label1.Text += e.KeyChar;

Page 191: Visual Programming

30: } 31: } 32: } 33: }

The KeyPress event will trigger whenever a button in your keyboard is pressed. Line 9 declares and initialize a counter variable named charCount that will be used to detect the number of characters of the current line This will be used for our simple word wrapping mechanism. The event handler monitors the number of characters typed by incrementing the charCount at Line 18. The condition at Line 21 tests whether the value of charCount doesn’t exceed 30. If so, it goes to the next line by adding the “\r\n” (carriage return-line feed) which is Windows’ way of proceeding to the next line. We then reset the charCount to 0 (Line 24) since we reached the beginning of the next line. If the charCount is still below or equal to 30, then we simply append the character typed by the user by using the KeyPressEventArgs.KeyChar property. When you execute the program, you can type letters using your keyboard and watch as the text inside the label is updated and the key you have just entered was appended to it’s text.

When you handle the KeyDown and KeyUp events, you get a different event argument named KeyEventArgs and it contains more properties about the pressed key. It contains the following properties.

Property DescriptionAlt Determines if the Alt button is pressed.Control Determines if the Control button is pressed.

KeyCodeGets the Keys value of the key that was pressed. It is used to detect a specific key that is pressed.

KeyDataSimilar to the KeyCode property but also records the modifier flags (SHIFT, CTRL, ALT) that are pressed.

KeyValue Returns the numeric representation of the key that was pressed.

ModifierDetermines which combination of modifiers flags (SHIFT, CTRL, ALT) is pressed.

Shift Tells whether the Shift key is pressed.SuppressKeyPress Allows you to prevent the user from giving an input from the keyboard.

As an example, the following code snippet uses the SupressKeyPress property of the KeyEventArgs to only allow numeric input and disallow any other characters such as alphabet or symbols. Add a text box to your form and add an event handler to its KeyDown event.

private void textBox1_KeyDown(object sender, KeyEventArgs e){ if (!(e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9 && !e.Shift)) { e.SuppressKeyPress = true; }}

The condition inside the if statement says that if the key typed by the user is not a number key, or if the shift key is pressed, then it will be ignored by setting the SuppressKeyPress property. We

Page 192: Visual Programming

used the KeyCode property in the condition which contains values from the Keys enumeration. The numeric keys are represented by values D0 to D9. The need to check if the Shift key is not pressed is needed since pressing Shift key and a numeric key will actually result in a symbol associated to the number key (@ to 2 for example). Therefore, we used the Shift property of the KeyEventArgs class.


Recommended