Learn Visual C# for College Students
5. More Exploration of the Visual C# Toolbox
Review and Preview
- In this class, we continue looking at tools in the Visual C# toolbox. We will look at some input tools, scroll bars, picture boxes and controls that allow direct interaction with drives, directories, and files. In the examples, you should start trying to do as much of the building and programming of the applications you can with minimal reference to the notes. This will help you build your programming skills.
Control Z Order
- As you build Windows applications using Visual C#, you will notice that whenever controls occupy the same space on a form, one control is on top of the other. The relative location of controls on a form is established by what is called the Z Order.
- As each control is placed on the form, it is assigned a Z Order value. Controls placed last will lie over controls placed earlier. While designing an application, the Z Order can be changed by right-clicking the control of interest. A menu will appear. Selecting BringToFront will bring that control ‘in front’ of all other controls. Conversely, selecting SendToBack will send that control ‘behind’ all other controls.
- A control’s Z Order can also be changed in code. Why would you want to do this? Perhaps, you have two controls on the form in exactly the same location, one that should be accessible for one particular operation and the other accessible for another operation. To place one control in front of the other, you need to change the Z Order. The BringToFront and SendToBack methods accomplish this task. For a control named controlExample, the code to accomplish this is:
controlExample.BringToFront();
Or
controlName.SendToBack();
- Now, let’s continue our look at the Visual C# toolbox, looking first at more controls that allow ‘point and click’ selections.
NumericUpDown Control
In Toolbox:
On Form (Default Properties):
- The NumericUpDown Control is used to obtain a numeric input. It looks like a text box control with two small arrows. Clicking the arrows changes the displayed value, which ranges from a specified minimum to a specified maximum. The user can even type in a value, if desired. Such controls are useful for supplying a date in a month or are used as volume controls in some Windows multimedia applications.
- NumericUpDown Properties:
Name Gets or sets the name of the numeric updown (three letter prefix for numeric updown name is nud).
BackColor Get or sets the numeric updown background color.
BorderStyle Gets or sets the border style for the updown control.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Increment Gets or sets the value to increment or decrement the updown control when the up or down buttons are clicked.
Maximum Gets or sets the maximum value for the updown control.
Minimum Gets or sets the minimum value for the updown control.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
TextAlign Gets or sets the alignment of text in the numeric updown.
Value Gets or sets the value assigned to the updown control.
- NumericUpDown Methods:
DownButton Decrements the value of the updown control.
UpButton Increments the value of the updown control.
- NumericUpDown Events:
Leave Occurs when the updown control loses focus.
ValueChanged Occurs when the Value property has been changed in some way (numeric updown control default event).
- The Value property can be changed by clicking either of the arrows or, optionally by typing a value. If using the arrows, the value will always lie between Minimum and Maximum. If the user can type in a value, you have no control over what value is typed. However, once the control loses focus, the typed value will be compared to Minimum and Maximum and any adjustments made. Hence, if you allow typed values, only check the Value property in the Leave event.
- Typical use of NumericUpDown control:
Ø Set the Name, Minimum and Maximum properties. Initialize Value property. Decide on value for ReadOnly.
Ø Monitor ValueChanged (or Leave) event for changes in Value.
Ø You may also want to change the Font, Backcolor and Forecolor properties.
DomainUpDown Control
In Toolbox:
On Form (Default Properties):
- The DomainUpDown control is similar in appearance to the NumericUpDown control. The difference is that the DomainUpDown control displays a list of string items (rather than numbers) as potential choices. It is much like a single line ComboBox control with no dropdown list. You will see it shares many of the properties of the ComboBox. The DomainUpDown control is usually reserved for relatively small lists. Examples of use are selecting a state in the United States for an address book, selecting a month for a calendar input or selecting a name from a short list.
- DomainUpDown Properties:
Name Gets or sets the name of the domain updown (three letter prefix for domain updown name is dud).
BackColor Get or sets the domain updown background color.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the domain updown.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
SelectedIndex Gets or sets the zero-based index of the currently selected item.
SelectedItem Gets or sets the selected item based on the index value of the selected item.
Sorted Gets or sets a value indicating whether items are sorted alphabetically.
Text Gets or sets the text displayed in the updown control.
TextAlign Gets or sets the alignment of the text in the updown control.
Wrap Gets or sets a value indicating whether the list of items continues to the first or last item if the user continues past the end of the list.
- DomainUpDown Methods:
DownButton Displays the next item in the control.
UpButton Displays the previous item in the control.
- DomainUpDown Events:
KeyPress Occurs when a key is pressed while the domain updown has focus.
Leave Occurs when the control loses focus.
SelectedItemChanged Occurs when the SelectedItem property has changed (the domain updown control default event).
TextChanged Occurs when the Text property has changed.
- Like the ListBox and ComboBox controls, the Items object provides details on what is in the control and how to add/delete information from the control. The first item in a updown control named dudExample is:
dudExample.Items.Item[0]
The last item in the list is:
dudExample.Items.Item[dudExample.Items.Count – 1]
- Items can be added at design time or in code. To add an item in design mode, click the Items property, then the ellipsis that appears. A dialog control will display allowing one entry per line. Click OK when done.
- To add an item in code, use the Add method, to delete an item, use the Remove or RemoveAt method and to clear it use the Clear method. For our example:
Add Item: dudExample.Items.Add(StringToAdd)
Delete Item: dudExample.Items.Remove(ItemToRemove)
DudExample.Items.RemoveAt(IndexOfItemToRemove)
Clear list box: dudExample.Items.Clear
- Typical use of DomainUpDown control:
Ø Set Name property, decide whether ReadOnly should be True and populate Items object (usually in form Load method).
Ø Monitor SelectedItemChanged (or TextChanged) event for individual selections.
Ø Read Text property to identify choice.
Ø As usual, you may also want to change the Font, Backcolor and Forecolor properties.
Example 5-1
Date Input Device
- Start a new project. In this project, we’ll use a NumericUpDown control, in conjunction with a DomainUpDown control, to select a month and day of the year.
- Place a NumericUpDown control, a DomainUpDown control and a Label control on the form. The form should resemble this:
- Set these properties:
Form1:
Name frmDate
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Date Input
domainUpDown1:
Name dudMonth
BackColor White
Font Size 14
ReadOnly True
Text December
Wrap True
numericUpDown1:
Name nudDay
BackColor White
Font Size 14
Maximum 31
Minimum 1
ReadOnly True
TextAlign Center
Value 1
label1:
Name lblDate
Font Size 12
Text [Blank]
When done, the form should look like this:
The label control cannot be seen.
- Use this code in the frmDate Load method to populate the control with the month names:
private void frmDate_Load(object sender, EventArgs e)
{
dudMonth.Items.Add(“January”);
dudMonth.Items.Add(“February”);
dudMonth.Items.Add(“March”);
dudMonth.Items.Add(“April”);
dudMonth.Items.Add(“May”);
dudMonth.Items.Add(“June”);
dudMonth.Items.Add(“July”);
dudMonth.Items.Add(“August”);
dudMonth.Items.Add(“September”);
dudMonth.Items.Add(“October”);
dudMonth.Items.Add(“November”);
dudMonth.Items.Add(“December”);
dudMonth.SelectedIndex = 0;
}
- Use this code in the dudMonth SelectedItemChanged event to update date if month changes:
private void dudMonth_SelectedItemChanged(object sender, EventArgs e)
{
lblDate.Text = dudMonth.Text + ” ” + nudDay.Value.ToString();
}
- Use this code in the nudDay ValueChanged event to update date if day changes:
private void nudDay_ValueChanged(object sender, EventArgs e)
{
lblDate.Text = dudMonth.Text + ” ” + nudDay.Value.ToString();
}
- Run the program. Here’s some selections I made:
Scroll through the month names. Notice how the Wrap property allows the list to return to January after December. Scroll through the day values, noticing how the displayed date changes. Save the project (saved in Example 5-1 folder in the LearnVCS2005\VCS2005 Code\Class 5 folder).
Do you notice that you could enter April 31 as a date, even though it’s not a legal value? Can you think of how to modify this example to make sure you don’t exceed the number of days in any particular month? And, how would you handle February – you need to know if it’s a leap year.
Horizontal and Vertical ScrollBar Controls
Horizontal ScrollBar In Toolbox:
Horizontal ScrollBar On Form (Default Properties):
Vertical ScrollBar In Toolbox:
Vertical ScrollBar On Form (Default Properties):
- The NumericUpDown control is useful for relatively small ranges of numeric input. It wouldn’t work well for large number ranges – you’d spend a lot of time clicking those little arrows. For large ranges of numbers, we use horizontal (HScrollBar) and vertical (VScrollBar) scroll bar controls. Scroll bars are widely used in Windows applications. Scroll bars provide an intuitive way to move through a list of information and make great input devices. Here, we use a scroll bar to obtain a whole number (Integer data type).
- Both types of scroll bars are comprised of three areas that can be clicked, or dragged, to change the scroll bar value. Those areas are:
End arrow |
Scroll box (thumb) |
Bar area |
Clicking an end arrow increments the scroll box a small amount, clicking the bar area increments the scroll box a large amount, and dragging the scroll box (thumb) provides continuous motion. Using the properties of scroll bars, we can completely specify how one works. The scroll box position is the only output information from a scroll bar.
- ScrollBar Properties (apply to both horizontal and vertical controls):
Name Gets or sets the name of the scroll bar (three letter prefix for horizontal scroll bar is hsb, for vertical scroll bar vsb).
LargeChange Increment added to or subtracted from the scroll bar Value property when the bar area is clicked.
Maximum The maximum value of the horizontal scroll bar at the far right and the maximum value of the vertical scroll bar at the bottom.
Minimum The minimum value of the horizontal scroll bar at the left and the vertical scroll bar at the top
SmallChange The increment added to or subtracted from the scroll bar Value property when either of the scroll arrows is clicked.
Value The current position of the scroll box (thumb) within the scroll bar. If you set this in code, Visual C# moves the scroll box to the proper position.
Location of properties for horizontal scroll bar:
SmallChange |
LargeChange |
Maximum |
Minimum |
SmallChange |
LargeChange |
Value |
Location of properties for vertical scroll bar:
Minimum |
SmallChange |
SmallChange |
LargeChange |
LargeChange |
Value |
Maximum |
- A couple of important notes about scroll bar properties:
- Notice the vertical scroll bar has its Minimum at the top and its Maximum at the bottom. This may be counter-intuitive in some applications. That is, users may expect things to ‘go up’ as they increase. You can give this appearance of going up by defining another variable that varies ‘negatively’ with the scroll bar Value property.
- If you ever change the Value, Minimum, or Maximum properties in code, make sure Value is at all times between Minimum and Maximum or the program will stop with an error message.
- ScrollBar Events:
Scroll Occurs when the scroll box has been moved by either a mouse or keyboard action (default scroll bar event).
ValueChanged Occurs whenever the scroll bar Value property changes, either in code or via a mouse action.
- Typical use of HScrollBar and VScrollBar controls:
Ø Decide whether horizontal or vertical scroll bar fits your needs best.
Ø Set the Name, Minimum, Maximum, SmallChange, LargeChange properties. Initialize Value property.
Ø Monitor Scroll or ValueChanged event for changes in Value.
- A Note on the Maximum Property:
For some reason, if LargeChange is not equal to one, the Maximum value cannot be achieved by clicking the end arrows, the bar area or moving the scroll box. It can only be achieved by setting the Value property in code. The maximum achievable Value, via mouse operations, is given by the relation:
Achievable Maximum = Maximum – LargeChange + 1
What does this mean? To meet an “achievable maximum,” you need to set the scroll bar Maximum property using this equation:
Maximum = Achievable Maximum + LargeChange – 1
For example, if you want a scroll bar to be able to reach 100 (with a LargeChange property of 10), you need to set Maximum to 109, not 100! Very strange, I’ll admit …
TrackBar Control
In Toolbox:
On Form (Default Properties):
- The TrackBar control is similar to the scroll bar control with a different interface. It is used to establish numeric input (usually a fairly small range). It can be oriented either horizontally or vertically.
- TrackBar Properties:
Name Gets or sets the name of the track bar (three letter prefix is trk).
LargeChange Increment added to or subtracted from the track bar Value property when the user clicks the track bar or presses the <PageUp> or <PageDn> keys.
Maximum The maximum value of the horizontal track bar at the far right and the maximum value of the vertical track bar at the top (this is different than the scroll bar).
Minimum The minimum value of the horizontal track bar at the left and the vertical track bar at the bottom.
Orientation Specifies a vertical or horizontal orientation for the control
SmallChange The increment added to or subtracted from the track bar Value property when user presses left or right cursor control keys (horizontal orientation); when user presses up or down cursor control keys (vertical orientation).
TickFrequency Determines how many tick marks appear on the track bar.
TickStyle Determines how and where ticks appear.
Value The current position of the pointer within the track bar. If you set this in code, Visual C# moves the pointer to the proper position.
- A couple of important notes about track bar properties:
- Notice the vertical track bar has its Maximum at the top. This is different than the vertical scroll bar control.
- If you ever change the Value, Minimum, or Maximum properties in code, make sure Value is at all times between Minimum and Maximum or the program will stop with an error message.
- The track bar Maximum property can be achieved in code or via mouse operations. It does not exhibit the odd behavior noted with the scroll bar control.
- TrackBar Events:
Scroll Occurs when the track bar pointer has been moved by either a mouse or keyboard action (default event for the track bar control).
ValueChanged Occurs whenever the track bar Value property changes, either in code or via a mouse action.
- Typical use of TrackBar control:
Ø Decide whether horizontal or vertical track bar fits your needs best.
Ø Set the Name, Minimum, Maximum, SmallChange, LargeChange properties. Initialize Value property.
Ø Monitor Scroll or ValueChanged event for changes in Value.
Example 5-2
Temperature Conversion
- Start a new project. In this project, we convert temperatures in degrees Fahrenheit (set using a horizontal scroll bar) to degrees Celsius. The formula for converting Fahrenheit (F) to Celsius (C) is:
C = (F – 32) * 5 / 9
Temperatures will be adjusted and displayed in tenths of degrees.
- Place a horizontal scroll bar, two labels and two text boxes on the form. Place two more labels (right behind each other, with AutoSize set to False so they can be resized) behind the scroll bar (we’ll use these for special effects). It should resemble this:
label3 and label4 |
- Set the properties of the form and each control:
Form1:
Name frmTemp
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Temperature Conversion
label1:
Font Bold, Size 10
Text Fahrenheit
textBox1:
Name txtTempF
BackColor White
Font Bold, Size 10
ReadOnly True
Text 32.0
TextAlign Center
label2:
Font Bold, Size 10
Text Celsius
textBox2:
Name txtTempC
BackColor White
Font Bold, Size 10
ReadOnly True
Text 0.0
TextAlign Center
Label3:
Name lblBlue
AutoSize False
BackColor Blue
Text [blank]
label4:
Name lbRed
AutoSize False
BackColor Red
Text [blank]
hScrollBar1:
Name hsbTemp
LargeChange 10
Maximum 1209
Minimum -600
SmallChange 1
Value 320
Note the scroll bar properties (Value, Minimum, Maximum, SmallChange, LargeChange) are in tenths of degrees. The initial temperatures are initialized at 32.0 F (Value = 320 tenths of degrees) and 0.0 C, known values. We want an “achievable maximum” of 120.0 degrees or a value of 1200. Why, then, is Maximum = 1209 and not 1200? Recall the formula for the actual Maximum to use is:
Maximum = Achievable Maximum + LargeChange – 1
Or, using our numbers:
Maximum = 1200 + 10 – 1 = 1209
When done, the form should look like this:
- Form level scope declarations:
bool isHot;
- Use this code in the hsbTemp Scroll event.
private void hsbTemp_Scroll(object sender, ScrollEventArgs e)
{
double tempF, tempC;
// Read F and convert to C – divide by 10 needed since Value is tenths of degrees
tempF = Convert.ToDouble(hsbTemp.Value) / 10;
// check to see if changed from hot to cold or vice versa
if (isHot && tempF < 70)
{
// changed to cold
isHot = false;
lblBlue.BringToFront();
hsbTemp.BringToFront();
}
else if (!isHot && tempF >= 70)
{
// changed to hot
isHot = true;
lblRed.BringToFront();
hsbTemp.BringToFront();
}
lblTempF.Text = String.Format(“{0:f1}”, tempF);
tempC = (tempF – 32) * 5 / 9;
lblTempC.Text = String.Format(“{0:f1}”, tempC);
}
This code determines the scroll bar Value as it changes, takes that value as Fahrenheit temperature, computes Celsius temperature, and displays both values. A blue label is used for cold temperatures, a red label for warm temperatures.
- Give the program a try. Make sure it provides correct information at obvious points. For example, 32.0 F better always be the same as 0.0 C! What happens around 70 F? Here’s a run I made:
Save the project (saved in Example 5-2 folder in the LearnVCS2005\VCS2005 Code\Class 5 folder).
Can you find a point where Fahrenheit temperature equals Celsius temperature? If you don’t know this off the top of your head, it’s obvious you’ve never lived in extremely cold climates. I’ve actually witnessed one of those bank temperature signs flashing degrees F and degrees C and seeing the same number! Ever wonder why body temperature is that odd figure of 98.6 degrees F? Can your new application give you some insight to an answer to this question?
PictureBox Control
In Toolbox:
On Form (Default Properties):
- Visual C# has powerful features for graphics. The PictureBox control is a primary tool for exploiting these features. The picture box control can display graphics files (in a variety of formats), can host many graphics functions and can be used for detailed animations. Here, we concentrate on using the control to display a graphics file.
- PictureBox Properties:
Name Gets or sets the name of the picture box (three letter prefix for picture box name is pic).
BackColor Get or sets the picture box background color.
BorderStyle Indicates the border style for the picture box.
Height Height of picture box in pixels.
Image Establishes the graphics file to display in the picture box.
Left Distance from left edge of form to left edge of picture box, in pixels.
SizeMode Indicates how the image is displayed.
Top Distance bottom of form title bar area to top edge of picture box, in pixels.
Width Width of picture box in pixels.
- PictureBox Events:
Click Triggered when a picture box is clicked (the picture box control default event).
- The Image property specifies the graphics file to display. It can be established in design mode or at run-time. Five types of graphics files can be viewed in a picture box:
File Type Description
Bitmap An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. This is the format commonly used by scanners and paintbrush programs. Bitmap filenames have a .bmp extension.
Icon A special type of bitmap file of maximum 32 x 32 size. Icon filenames have an .ico extension. We’ll create icon files in Class 5
Metafile A file that stores an image as a collection of graphical objects (lines, circles, polygons) rather than pixels. Metafiles preserve an image more accurately than bitmaps when resized. Many graphics files available for download from the internet are metafiles. Metafile filenames have a .wmf extension.
JPEG JPEG (Joint Photographic Experts Group) is a compressed bitmap format which supports 8 and 24 bit color. It is popular on the Internet and is a common format for digital cameras. JPEG filenames have a .jpg extension.
GIF GIF (Graphic Interchange Format) is a compressed bitmap format originally developed by CompuServe. It supports up to 256 colors and is also popular on the Internet. GIF filenames have a .gif extension.
- Setting the Image property in design mode requires a few steps. Let’s do an example to illustrate the process. Start a new project and put a picture box control on the form. Mine looks like this:
- Graphics files used at design-time are saved as program Resources. Once these resources are established, they can be used to set the Image property. The process to follow is to display the Properties window for the picture box control and select the Image property. An ellipsis (…) will appear. Click the ellipsis. A Select Resource window will appear. Make sure the Project resource file radio button is selected and click the button marked Import – a file open window will appear. Move (as shown) to the \LearnVCS2005\VCS2005 Code\Class 5\Example 5-3 folder and you will see some sample files listed:
We have included one of each file type. There is a bitmap picture of a beany (beany.bmp), a metafile of an answering machine (answer.wmf), a copy of the KIDware logo (kidware.gif) and a picture from my Mexico vacation (mexico.jpg). Notice there is no icon file (ico extension). By default, icon files are not displayed. To see the icon file (a CD-ROM), click the drop-down box next to Files of type and choose All Files. All files (including the ico file and even non-graphics files will be displayed). Hence, if you need an icon file in a picture box, you must take an extra step to select it. Select all five graphics files and click Open.
- You should now see the Select Resource window, with all five files now added to the program resources. Individual images are selected using this window:
Select the beany graphic (a bitmap) and click the OK button. It will be displayed in the picture box on our form:
- To set the Image property at run-time, you use the FromFile method associated with the Image object. As an example, to load the file c:\sample\myfile.bmp into a picture box name picExample, the proper code is:
picExample.Image = Image.FromFile(“c:\sample\myfile.bmp”);
The argument in the Image.FromFile method must be a legal, complete path and file name, or your program will stop with an error message.
- To clear an image from a picture box control at run-time, simply set the corresponding Image property to null (a C# keyword). This disassociates the Image property from the last loaded image. For our example, the code is:
picExample.Image = null;
- The SizeMode property dictates how a particular image will be displayed. There are four possible values for this property: Normal, CenterImage, StretchImage, AutoSize. The effect of each value is:
SizeMode Effect
Normal Image appears in original size. If picture box is larger than image, there will be blank space. If picture box is smaller than image, the image will be cropped.
CenterImage Image appears in original size, centered in picture box. If picture box is larger than image, there will be blank space. If picture box is smaller than image, image is cropped.
StretchImage Image will ‘fill’ picture box. If image is smaller than picture box, it will expand. If image is larger than picture box, it will scale down. Bitmap and icon files do not scale nicely. Metafiles, JPEG and GIF files do scale nicely.
AutoSize Reverse of StretchImage – picture box will change its dimensions to match the original size of the image. Be forewarned – metafiles are usually very large!
Zoom Similar to StretchImage. The image will adjust to fit within the picture box, however its actual height to width ratio is maintained.
Notice picture box dimensions remain fixed for Normal, CenterImage, StretchImage, and Zoom SizeMode values. With AutoSize, the picture box will grow in size. This may cause problems at run-time if your form is not large enough to ‘contain’ the picture box.
- Typical use of PictureBox control for displaying images:
Ø Set the Name and SizeMode property (most often, StretchImage).
Ø Set Image property, either in design mode or at run-time.
OpenFileDialog Control
In Toolbox:
Below Form (Default Properties):
- Note that to set the Image property of the picture box control using the FromFile method, you need the path and filename for the image file. How can you get this from a user? One possibility would be to use a text box control, asking the user to type in the desired information? This is just asking for trouble. Even the simplest of paths is difficult to type, remembering drive names, proper folder names, file names and extensions, and where all the slashes go. And then you, the programmer, must verify that the information typed contains a valid path and valid file name.
- I think you see that asking a user to type a path and file name is a bad idea. We want a ‘point and click’ type interface to get a file name. Every Windows application provides such an interface for opening files. [Click on the Open File toolbar button in Visual C# and an ‘Open File’ dialog box will appear.] Visual C# lets us use this same interface in our applications via the OpenFileDialog control. This control is one of a suite of dialog controls we can add to our applications. There are also dialog controls to save files, change fonts, change colors, and perform printing operations. We’ll look at other dialog controls as we work through the course.
- What we learn here is not just limited to opening image files for the picture box control. There are many times in application development where we will need a file name from a user. Applications often require data files, initialization files, configuration files, sound files and other graphic files. The OpenFileDialog control will also be useful in these cases.
- OpenFileDialog Properties:
Name Gets or sets the name of the open file dialog (I usually name this control dlgOpen).
AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
DefaultExt Gets or sets the default file extension.
FileName Gets or sets a string containing the file name selected in the file dialog box.
Filter Gets or sets the current file name filter string, which determines the choices that appear in “Files of type” box.
FilterIndex Gets or sets the index of the filter currently selected in the file dialog box.
InitialDirectory Gets or sets the initial directory displayed by the file dialog box.
Title Gets or sets the file dialog box title.
- OpenFileDialog Methods:
ShowDialog Displays the dialog box. Returned value indicates which button was clicked by user (OK or Cancel).
- To use the OpenFileDialog control, we add it to our application the same as any control. Since the OpenFileDialog control has no immediate user interface (you control when it appears), the control does not appear on the form at design time. Such Visual C# controls (the Timer control seen briefly back in Chapter 1 was a similar control) appear in a ‘tray’ below the form in the IDE Design window. Once added, we set a few properties. Then, we write code to make the dialog box appear when desired. The user then makes selections and closes the dialog box. At this point, we use the provided information for our tasks.
- The ShowDialog method is used to display the OpenFileDialog control. For a control named dlgOpen, the appropriate code is:
rtnValue = dlgOpen.ShowDialog();
And the displayed dialog box is similar to:
- The user selects a file using the dialog control (or types a name in the File name box). The file type is selected form the Files of type box (values here set with the Filter property). Once selected, the Open button is clicked. Cancel can be clicked to cancel the open operation. The ShowDialog method returns (in rtnValue in the above example code) the clicked button. It returns DialogResult.OK if Open is clicked and returns DialogResult.Cancel if Cancel is clicked. The nice thing about this control is that it can validate the file name before it is returned to the application. The FileName property contains the complete path to the selected file.
- Typical use of OpenFileDialog control:
Ø Set the Name, Filter, and Title properties.
Ø Use ShowDialog method to display dialog box.
Ø Read FileName property to determine selected file
Example 5-3
Picture Box Playground
- Start a new project. In this project, we will use a OpenFileDialog control to select image files. The selected file will be displayed in five different picture box controls (one for each setting of the SizeMode property).
- Place five labels on a form. Place a picture box control under each of the labels. Place another label, a text box and a button control under these controls. Finally, place the OpenFileDialog control in the ‘tray’ under the form. The form (which will be rather wide) should look like this:
pictureBox5 |
pictureBox4 |
pictureBox3 |
pictureBox2 |
pictureBox1 |
Other controls in tray:
- Set the properties of the form and each control:
Form1:
Name frmPlayground
Text Picture Box Playground
label1:
Text Normal:
label2:
Text CenterImage:
label3:
Text StretchImage:
label4:
Text AutoSize:
label5:
Text Zoom:
pictureBox1:
Name picNormal
BackColor White
BorderStyle FixedSingle
SizeMode Normal
pictureBox2:
Name picCenter
BackColor White
BorderStyle FixedSingle
SizeMode CenterImage
pictureBox3:
Name picAuto
BackColor White
BorderStyle FixedSingle
SizeMode AutoSize
pictureBox4:
Name picStretch
BackColor White
BorderStyle FixedSingle
SizeMode StretchImage
pictureBox5:
Name picZoom
BackColor White
BorderStyle FixedSingle
SizeMode Zoom
label6:
Text Size:
textBox1:
Name txtSize
TextAlign Center
button1:
Name btnImage
Text &Select Image
openFileDialog1:
Name dlgOpen
FileName [blank]
Filter Bitmaps (*.bmp)|*.bmp|Icons (*.ico)|*.ico|Metafiles (*.wmf)|*.wmf|JPEG (*.jpg)|*.jpg|GIF (*.gif)|*.gif
[Type this line carefully! – consult on-line help as reference]
Title Open Image File
When done, the form should look like this:
Other controls in tray:
- Form level scope declarations:
int wSave, hSave;
- Use this code in the frmPlayground Load event to initialize positions and save size:
private void frmPlayground_Load(object sender, EventArgs e)
{
// start form in upper left corner
this.Left = 0;
this.Top = 0;
// save form width/height for initialization
wSave = this.Width;
hSave = this.Height;
}
- Use this code in the btnImage Click event:
private void btnImage_Click(object sender, EventArgs e)
{
// reset autosize picture box and form to initial size
picAuto.Width = picNormal.Width;
picAuto.Height = picNormal.Height;
this.Width = wSave;
this.Height = hSave;
// display open dialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
picNormal.Image = Image.FromFile(dlgOpen.FileName);
picCenter.Image = Image.FromFile(dlgOpen.FileName);
picAuto.Image = Image.FromFile(dlgOpen.FileName);
picStretch.Image = Image.FromFile(dlgOpen.FileName);
picZoom.Image = Image.FromFile(dlgOpen.FileName);
txtSize.Text = picAuto.Width.ToString() + ” x ” + picAuto.Height.ToString();
}
}
This code reads the selected file and displays it in each of the picture box controls.
- Save the application (saved in Example 5-3 folder in the LearnVCSE\VCSE Code\Class 5 folder). Run the application and open different types of image files (we’ve included one of each type in the project folder). Here’s a beany in bitmap format:
Notice how the different SizeMode properties affect the display. Images in the AutoSize mode may be very large requiring resizing of the form.
Look for the folder Visual C# (or Visual Studio) is installed in. On my computer it is c:\Program Files\Microsoft Visual Studio 8. In the Common7\VS2005ImageLibrary folder of that folder is a zipped file named VS2005ImageLibrary. If you unzip this file to your computer, there will be folders of many graphics you can view and use.
Legacy Controls
- In the Picture Box Playground example just developed, every time we want to change the image, it is necessary to bring up the open file dialog box. What would be nice is to have the capability of the dialog box built into the form providing a clickable list of image files, directories and drives. As each file name was clicked, the corresponding image would be displayed in each of the picture boxes. Controls to build such a built-in dialog box exist, but they are not part of Visual C# – they are part of Visual Basic, another programming language, but we can still use them like any other control. (One caveat – since the controls discussed in this section are from Visual Basic, you must be using Visual Studio, making sure Visual Basic is included in your installation. If Visual Basic is not part of your current Visual Studio installation, you will have to do a reinstall. If you are using a stand-alone Visual C# product, you cannot complete the remaining example.)
- We will be using three controls. The DriveListBox control is a dropdown box that allows selection of drives. The DirListBox control is a list box allowing folder selection. And, the FileListBox control is a list box allowing file selection. Using these three controls on a form allows a ‘built-in’ replication of the open file dialog box. And, the nice thing about these controls is you can use as many (or as few) as you like. For example, if you just want to present your user a selection of files in a single directory they could not change, you just use the FileListBox control. The OpenFileDialog control does not allow such a limitation.
- The controls we are using are referred to as legacy controls. These are controls that existed in previous versions of a product and have been eliminated in current versions. For the most part, elimination of these legacy controls is a good thing, providing a more up-to-date product. But the three controls discussed here have real utility – we wish they had not been eliminated.
- So, are we just left with our ‘wishing and hoping’ these controls were back? Unfortunately, no. Visual C# still has some of these legacy controls (as part of the Microsoft.Visual Basic.Compatibility.VB6 namespace), but they must be added to the toolbox. To do this, click the Tools menu item and select Choose Toolbox Items. When the dialog box appears, select .NET Framework Components. Place check marks next to: DriveListBox, DirListBox and FileListBox. Click OK and the controls will appear in the toolbox and become available for use (on-line help is available for documentation).
- You may see other legacy controls in the Customize Toolbox dialog box. You can decide if you need any other such controls. Be aware, however, that using legacy controls could be dangerous. Microsoft may decide to drop support for such controls at any time. Our hope is that controls similar to the drive, directory and file list tools are added with the next version of Visual Studio – their utility calls out for their inclusion.
DriveListBox Controls
In Toolbox:
On Form (Default Properties):
- The DriveListBox control allows a user to select a valid disk drive at run-time. It displays the available drives in a drop-down combo box. No code is needed to load a drive list box with valid drives; the control does this for us. We use the box to get the current drive identification.
- DriveListBox Properties:
Name Gets or sets the name of the drive list box (three letter prefix for drive list box name is drv).
BackColor Get or sets the drive list box background color.
Drive Contains the name of the currently selected drive.
DropDownStyle Gets or sets a value specifying the style of the drive list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
- DriveListBox Events:
SelectedValueChanged Triggered whenever the user or program changes the drive selection.
- This control is always used in conjunction with the DirListBox and FileListBox controls – we rarely look at the Drive property.
- Typical use of DriveListBox control:
Ø Set the Name property.
Ø Use SelectedValueChanged event to update displayed directories.
DirListBox Control
In Toolbox:
On Form (Default Properties):
- The DirListBox control displays an ordered, hierarchical list of the user’s disk directories and subdirectories. The directory structure is displayed in a list box. Like, the drive list box, little coding is needed to use the directory list box – the control does most of the work for us.
- DirListBox Properties:
Name Gets or sets the name of the directory list box (three letter prefix for directory list box name is dir).
BackColor Get or sets the directory list box background color.
BorderStyle Establishes the border for directory list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Path Gets or sets the current directory path.
- DirListBox Events:
Change Triggered when the directory selection is changed.
- Typical use of DirListBox control:
Ø Set the Name property.
Ø Use Change event to update displayed files.
Ø Read Path property for current path.
FileListBox Control
In Toolbox:
On Form (Default Properties):
- The FileListBox control locates and lists files in the directory specified by its Path property at run-time. You may select the types of files you want to display in the file list box. You will notice most of its properties are very similar to those of the list box control studied in Class 3.
- FileListBox Properties:
Name Gets or sets the name of the file list box (three letter prefix for file list box name is fil).
BackColor Get or sets the file list box background color.
FileName Contains the currently selected file name.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the file list box.
Path Contains the current path directory.
Pattern Contains a string that determines which files will be displayed. It supports the use of * and ? wildcard characters. For example, using *.dat only displays files with the .dat extension.
SelectedIndex Gets or sets the zero-based index of the currently selected item in a list box.
SelectionMode Gets or sets the method in which items are selected in file list box (allows single or multiple selections).
- FileListBox Events:
SelectedIndexChanged Occurs when the SelectedIndex property has changed (default event for this control).
- If needed, the number of items in the list is provided by the Items.Count property. The individual items in the list are found by examining elements of the Items.Item zero-based array.
- Typical use of FileListBox control:
Ø Set Name and Pattern properties.
Ø Monitor SelectedIndexChanged event for individual selections.
Ø Use Path and FileName properties to form complete path to selected file.
Synchronizing the Drive, Directory, and File List Box Controls
- The drive, directory and file list boxes are controls that can be used independently of each other. As such, there are no common properties or linking mechanisms. When used with each other to obtain a file name, their operation must be synchronized to insure the displayed information is always consistent.
- When the drive selection is changed (drive list box SelectedValueChanged event), you need to update the directory list box path. For example, if the drive list box is named drvExample and the directory list box is dirExample, use the code:
dirExample.Path = drvExample.Drive;
- When the directory selection is changed (directory list box Change event), you must update the names displayed in the file list box. With a file list box named filExample, this code is:
filExample.Path = dirExample.Path;
- Once all of the selections have been made and you want the file name, you need to form a text string that specifies the complete path to the file. This string concatenates the Path and FileName information from the file list box. This should be an easy task, except for one problem. The problem involves the backslash (\) character. If you are at the root directory of your drive, the path name ends with a backslash. If you are not at the root directory, there is no backslash at the end of the path name and you have to add one before tacking on the file name.
- Example code for concatenating the available information into a proper file name (yourFile):
string yourName;
string yourPath = filExample.Path;
if (yourPath[yourPath.Length – 1] == ‘\\’)
{
yourFile = yourPath + filExample.FileName;
}
else
{
yourFile = yourPath + “\\” + filExample.FileName;
}
This code checks the last character in the Path property to see if it is a backslash [we need to use two characters (\\) to represent a backslash to distinguish it from C# escape characters]. Note we only have to use properties of the file list box. The drive and directory box properties are only used to create changes in the file list box via code.
Example 5-4
Image Viewer
- Start a new project. In this application, we search our computer’s file structure for graphics files and display the results of our search in an picture box control.
- First, place a group box control on the form. In this group box, place a drive list box, directory list box, file list box, a text box and three labels. Make sure you have added the three legacy list box controls to your toolbox using instructions provided earlier. Add a second group box. In that group box, place a picture box control and four radio buttons. The form should look like this:
pictureBox1 |
- Set properties of the form and each control.
Form1:
Name frmImage
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Image Viewer
groupBox1:
Name grpFile
BackColor Red
Text [Blank]
txtBox1:
Name txtImage
BackColor Yellow
MultiLine True
label1:
ForeColor Yellow
Text Files:
driveListBox1:
Name drvImage
label2:
ForeColor Yellow
Text Directories:
dirListBox1:
Name dirImage
label3:
ForeColor Yellow
Text Drives:
fileListBox1:
Name filImage
Pattern *.bmp;*.ico;*.wmf;*.gif;*.jpg
[type this line with no spaces]
groupBox1:
Name grpImage
BackColor Blue
Text [Blank]
pictureBox1:
Name picImage
BackColor White
BorderStyle FixedSingle
radioButton1:
Name rdoNormal
ForeColor Yellow
Text Normal
radioButton2:
Name rdoCenter
ForeColor Yellow
Text Center
radioButton3:
Name rdoStretch
ForeColor Yellow
Text Stretch
radioButton4:
Name rdoZoom
ForeColor Yellow
Text Zoom
My finished form is this:
- Use this code in the frmImage Load method (initializes Stretch size mode):
private void frmImage_Load(object sender, EventArgs e)
{
// initialize stretch mode
rdoStretch.PerformClick();
}
- Use this code in the drvImage SelectedValueChanged method.
private void drvImage_SelectedValueChanged(object sender, EventArgs e)
{
// If drive changes, update directory
dirImage.Path = drvImage.Drive;
}
When a new drive is selected, this code forces the directory list box to display directories on that drive.
- Use this code in the dirImage Change method.
private void dirImage_Change(object sender, EventArgs e)
{
// If directory changes, update file path
filImage.Path = dirImage.Path;
}
Likewise, when a new directory is chosen, we want to see the files on that directory.
- Use this code for the filImage SelectedIndexChanged event.
private void filImage_SelectedIndexChanged(object sender, EventArgs e)
{
// Get complete path to file name and open graphics
string imageName;
string imagePath = filImage.Path;
if (imagePath[imagePath.Length – 1] == ‘\\’)
{
imageName = imagePath + filImage.FileName;
}
else
{
imageName = imagePath + “\\” + filImage.FileName;
}
txtImage.Text = imageName;
picImage.Image = Image.FromFile(imageName);
}
This code forms the file name (ImageName) by concatenating the directory path with the file name. It then displays the complete name and loads the image into the picture box.
- Lastly, code the four radio button CheckedChanged events to change the display size mode:
private void rdoNormal_CheckedChanged(object sender, EventArgs e)
{
picImage.SizeMode = PictureBoxSizeMode.Normal;
}
private void rdoCenter_CheckedChanged(object sender, EventArgs e)
{
picImage.SizeMode = PictureBoxSizeMode.CenterImage;
}
private void rdoStretch_CheckedChanged(object sender, EventArgs e)
{
picImage.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void rdoZoom_CheckedChanged(object sender, EventArgs e)
{
picImage.SizeMode = PictureBoxSizeMode.Zoom;
}
- Save your project (saved in Example 5-4 folder in LearnVCSE\VCSE Code\Class 5 folder). Run and try the application. Find bitmaps, icons, metafiles, gif files, and JPEGs (an example of each is included in the project folder). Here’s how the form should look when displaying the example JPEG file (a photo from my Mexican vacation):
Note the picture is distorted a bit. Click the Zoom mode and you’ll see the height to width ratio is correct.
Class Review
- After completing this class, you should understand:
Ø The concept of Z Order for a control
Ø Useful properties, events, methods and typical uses for the numeric updown and domain updown controls
Ø Properties, events, methods, and uses for the horizontal and vertical scroll bar controls
Ø The five types of graphics files that can be displayed by the picture box control
Ø How the picture box SizeMode property affects Image display
Ø How to load image files at both design time and run time
Ø How to use the file open common dialog box to obtain file names for opening files
Ø How the legacy drive, directory, and file list controls work and when they could be used
Practice Problems 5
Problem 5-1. Tic-Tac-Toe Problem. Build a simple Tic-Tac-Toe game. Use ‘skinny’ label controls for the grid and picture box controls for markers (use different pictures to distinguish players). Click the picture box controls to add the markers. Can you write logic to detect a win?
Problem 5-2. Number Guess Problem. Build a game where the user guesses a number between 1 and 100. Use a scroll bar for entering the guess and change the extreme limits (Minimum and Maximum properties) with each guess to help the user adjust their guess.
Problem 5-3. File Times Problem. Using the drive, directory and file list controls, write an application that lists all files in a directory. For every file, find what time the file was created (use the FileInfo object from the System.IO namespace). Determine the most popular hours of the day for creating files.
Exercise 5
Student Database Input Screen
You did so well with last chapter’s assignment that, now, a school wants you to develop the beginning structure of an input screen for its students. The required input information is:
- Student Name
- Student Grade (1 through 6)
- Student Sex (Male or Female)
- Student Date of Birth (Month, Day, Year)
- Student Picture (Assume they can be loaded as jpeg files)
Set up the screen so that only the Name needs to be typed; all other inputs should be set with option buttons, scroll bars, and common dialog boxes. When a screen of information is complete, display the summarized profile in a message box. This profile message box should resemble this:
Note the student’s age must be computed from the input birth date – watch out for pitfalls in doing the computation. The student’s picture does not appear in the profile, only on the input screen.