UNIT-IV
UNIT-IV
NET
TEXTBOX:Windows forms text boxes are used to get input from the user or to display text. The TextBox
control is generally used for editable text, although it can also be made read-only,have scroll bars. Text boxes
can display multiple lines, wrap text to the size of the control, and add basic formatting, such as quotation marks
and masking characters for passwords.
The TextBox class is derived from the TextBoxBase class, which is based on Control:
Object
MarshalByRefObject
Component
Control
TextBoxBase
TextBox
Table : Noteworthy public properties of TextBox objects.
Property Means
AutoSize Sets/gets a value specifying if the height of the control automatically adjusts
when the font in the control is changed.
BackColor Sets/gets the background color of the control.
BorderStyle Sets/gets the border type of the text box control.
CanUndo Returns a value specifying if the user can undo the previous operation.
ForeColor Sets/gets the foreground color.
HideSelection Sets/gets a value specifying if the selected text in the text box control
remains highlighted when the text box loses focus.
Lines Sets/gets the lines of text.
MaxLength Sets/gets the maximum number of characters the user can type into the text
box.
Modified Indicates if the text box control has been modified by the user since the
control was created or its contents were last set.
Multiline Sets/gets a value specifying if this is a multiline text box control.
PasswordChar Sets/gets the character used to mask characters of a password in a single-
line text box.
ReadOnly Sets/gets a value specifying if text in the text box is read-only.
ScrollBars Sets/gets what scroll bars should appear in a multiline text box.
SelectedText Sets/gets a value specifying the currently selected text in the control.
SelectionLength Sets/gets the number of characters selected in the text box.
SelectionStart Sets/gets the starting point of text selected in the text box.
Text Sets/gets the current text in the text box.
TextAlign Sets/gets how text is aligned in a text box control.
TextLength Gets the length of text in the control.
WordWrap Indicates if a multiline text box control automatically wraps words.
The text displayed by the control is contained in the Text property. By default, you can enter up to 2,048
characters in a text box. If you set the MultiLine property to True to make the control accept multiple lines of
text, you can enter up to 32KB of text. The Text property can be set at design time with the Properties window,
at run time in code, or by user input at run time. The current contents of a text box can be retrieved at run time
by reading the Text property. We've seen how to do this already, as in this example, which inserts text into a
text box:
You can set or read text from text boxes at run time, and the user can enter and edit text in text boxes as well.
You can limit the amount of text entered into a TextBox control by setting the MaxLength property to a
specific number of characters. TextBox controls also can be used to accept passwords if you use the
PasswordChar property to mask characters.
And you can restrict any data entry in a TextBox control by setting the ReadOnly property to True.
For multiline text boxes, it would be even better if you could add scroll bars to let the user
enter even more text. Using the ScrollBars property, there are four ways to add scroll bars to
a text box.
0: None
1: Horizontal
2: Vertical
3: Both
Note that in order for the scroll bars to actually appear, the text box's MultiLine property
must be True.
text boxes have an TextAlign property, so you set it to Centered (there are three possibilities:
0: left-justified, 1: right-justified, and 2: centered) at design time in all the text boxes.
ReadOnly Property
Setting this property to True means that the user cannot enter text into the text box.
You also can disable a text box by setting its Enabled property to False. However, although
this means the user can't enter text into the text box, it also means the text in the box appears
grayed. Disabling is better done to indicate that the control is inaccessible.
To convert a standard text box into a password box, you just assign some character (usually
an asterisk, "*") to the text box's PasswordChar property. After that, your program can read
the text in the text box, but only the password character will appear on the screen each time
the user types a character.
LABEL: Labels usually are used to display text that cannot be edited by the user. Your code
can change the text displayed by a label. Labels are based directly on the Control class:
Object
MarshalByRefObject
Component
Control
Label
Noteworthy public properties of Label objects.
Property Means
AutoSize Sets/gets a value specifying if the control should be automatically resized
to display all its contents.
BorderStyle Sets/gets the border style for the control.
FlatStyle Sets/gets the flat style appearance of the label control.
Image Sets/gets the image that is displayed on a Label.
ImageAlign Sets/gets the alignment of an image that is displayed in the control.
PreferredHeight Gets the preferred height of the control.
PreferredWidth Gets the preferred width of the control.
TextAlign Sets/gets the alignment of text in the control.
UseMnemonic Sets/gets a value specifying if the control treats an ampersand character (&)
in the control's Text property to be an access key character.
The caption for a label is stored in the Text property. Because you can change that caption in
code, labels can act a little like non-editable text boxes, displaying text and messages to the
user. The TextAlign (formerly Alignment) property allows you to set the alignment of the
text within the label.
To make a text box look like a label, set the text box's BackColor property to Control in the
popup box that appears when you set this property in the properties window; its ReadOnly
property to True; and its BorderStyle property to None. To make a label look like a text
box, set its BackColor property to Window and its BorderStyle property to Fixed3D.
Label1.backcolor=Color.Red;
Label1.BorderStyle=BorderStyle.Fixed3D;
Make the label match the text's size by setting the AutoSize property to True.format the text
in a label with the Font property, setting it to a Font object.
Label1.Font=FonStyle.BOLD;
Aligning Text
set the label's TextAlign property at design time or run time. This property takes values from
the ContentAlignment enumeration:
Buttons
Buttons are the plain controls that you simply click and release, the buttons you see
everywhere in Visual Basic applications-usually just rounded rectangular, gray buttons with a
caption
Button class is based on the Control class. In fact, the Button class is based directly on the
ButtonBase class
Object
MarshalByRefObject
Component
Control
ButtonBase
Button
Noteworthy public properties of Button objects.
Property Means
DialogResult Gets/sets the value returned to the parent form when the button is clicked.
Often used when you're creating dialog boxes.
FlatStyle Gets/sets a flat style appearance.
Image Gets/sets an image displayed in a button.
ImageAlign Gets/sets the alignment of the image in a button.
ImageIndex Gets/sets the image list index value of the image displayed in the button.
ImageList Gets/sets the ImageList that contains the images displayed in a button.
TextAlign Gets/sets the alignment of the text in the button.
Table 6.2: Noteworthy public methods of Button objects.
Method Means
PerformClick Causes a Click event for a button.
You use a button's Text property (formerly the Caption property in VB6 and before) to set
its caption. This property is available at both design time and run time.
You also can set the button's Background property at run time, setting it to a color value,
such as those in the Visual Basic Color enumeration
set the foreground color of a button—the color of the caption's text. Much like the
BackColor property, you can set a button's ForeColor property at design time, or at run
time, like this:
Selecting the Font item in the property window and then clicking the ellipsis ("…") button
that appears opens the Font dialog. you can see all kinds of fonts and settings for buttons'
captions, and the Microsoft Sans Serif font goes up to 72 points.
You also can set the Font property of a button at run time.
To add a click event handler, just double-click the button at design time
Place the code you want to execute when the button is clicked
TabStop indicates if this button can accept the focus when the user tabs to it.
TabIndex is the index of the current button in the tab order (starts at 0).
When the user presses the Tab key, the focus moves from button to button, ascending through
the tab order.
Checkboxes
Checkboxes are also familiar controls—you click a checkbox to select it, and click it again to
deselect it. When you select a checkbox, a check appears in it, indicating that the box is
indeed selected. You use a checkbox to give the user an option, such as true/false or yes/no.
The checkbox control can display an image or text or both.
You can handle checkbox CheckChanged events, which happen when the Checked property
changes
{
TextBox1.Text = "You clicked check box 1";
}
It displays the output as follows:
You can see if a checkbox is checked by examining its Checked property. This property can
be set to either True or False.
I will change a button's caption if a checkbox, CheckBox1, is checked, but not otherwise:
You can set a checkbox's state by setting its Checked property to True or False, as in this
code:
By default, checkboxes are two-state controls; you use the Checked property to get or set the
value of a two-state checkbox. However, if you set the checkbox's ThreeState property to
True, you make the checkbox into a three-state control.
You use the CheckState property to get or set the value of the three-state checkbox. The
three states are:
Set the checkbox's ThreeState property to True, you can set its CheckState property to
CheckState.Indeterminate at design time or run time to set the checkbox to the
indeterminate state:
Radio Buttons
Radio buttons, also called option buttons, are similar to checkboxes—the user can select and
deselect them—except for two things: they are round where checkboxes are square, and you
usually use radio buttons together in groups.
In fact, that's the functional difference between checkboxes and radio buttons—checkboxes
can work independently, but radio buttons are intended to work in groups. When you select
one radio button in a group, the others are automatically deselected.
Object
MarshalByRefObject
Component
Control
ButtonBase
RadioButton
You can find the more notable public properties of the RadioButton class in Table 6.5, the
notable methods in Table 6.6, and the notable events in Table 6.7, including those inherited
from the ButtonBase class. Note that as with other controls, I am not listing the notable
properties, methods, and events RadioButton inherits from the Control class, such as the
Click event—you can see all that in Chapter 5, Tables 5.1, 5.2, and 5.3.
You can handle radio button CheckChanged events, which happen when the Checked
property changes;
}
It displays the output as follows:
Here's an example showing how to determine whether a radio button is selected or not. In this
case, we display a message in a message box that indicates if a radio button, RadioButton1,
is selected or not:
You can turn checkboxes or radio buttons into toggle buttons if you set their Appearance
property to Button (the other option is Normal). Toggle buttons resemble standard buttons
but act like the checkboxes or radio buttons they really are.
click the "Create toggle buttons" button to change the appearance of radio buttons at run time.
Here's the code that does the trick:
LIST BOXES:
List boxes display a list of items from which the user can select one or more. If there are too
many items to display at once, a scroll bar automatically appears to let the user scroll through
the list. In Visual Basic .NET, each item in a list box is itself an object.
You also can scroll list boxes horizontally when you set the MultiColumn property to True.
Alternatively, when the ScrollAlwaysVisible property is set to True, a scroll bar always
appears.
You can keep track of the selected item in a list box two ways—by numeric index (starting at
0) or by accessing the selected item's object directly. The SelectedIndex property returns an
integer value that corresponds to the selected item. If the first item in the list is selected, then
the SelectedIndex value is 0. You can change the selected item by changing the
SelectedIndex value in code; the corresponding item in the list will appear highlighted on the
Windows form. If no item is selected, the SelectedIndex value is -1. You also can set which
items are selected with the SetSelected method in code.
The SelectedItem property is similar to SelectedIndex, but returns the object corresponding
to the item itself.
The items in list boxes are stored in the Items collection; the Items.Count property holds the
number of items in the list. (The value of the Items.Count property is always one more than
the largest possible SelectedIndex value because SelectedIndex is zero-based.) To add or
delete items in a ListBox control, you can use the Items.Add, Items.Insert, Items.Clear, or
Items.Remove methods. You also can add a number of objects to a list box at once with the
AddRange method. Or you can add and remove items to the list by using the Items property
at design time.
You also can support multiple selections in list boxes. The SelectionMode property
determines how many list items can be selected at a time; you can set this property to None,
One, MultiSelect, or MultiExtended:
MultiExtended— Multiple items can be selected, and the user can use the Shift, Ctrl,
and arrow keys to make selections.
MultiSimple— Multiple items can be selected.
None— No items may be selected.
One— Only one item can be selected.
Object
MarshalByRefObject
Component
Control
ListControl
ListBox
public properties of ListBox objects.
Property Means
ColumnWidth Gets/sets column width; use with multicolumn list boxes.
DisplayMember Indicates which property of objects in a list box to show. If this
property if empty, the object's ToString method is used.
DrawMode Gets/sets the drawing mode for the list box.
HorizontalExtent Gets/sets the width a list box can scroll horizontally.
HorizontalScrollbar Gets/sets if a horizontal scroll bar is displayed in the list box.
IntegralHeight Gets/sets if the list box should resize so it doesn't show partial items.
ItemHeight Gets/sets an item's height in the list box.
Items Returns a collection of the items of the list box.
MultiColumn Gets/sets if the list box supports multiple columns.
PreferredHeight Returns the total height of all items in the list box.
ScrollAlwaysVisible Gets/sets if a vertical scroll bar is always shown.
SelectedIndex Gets/sets the index of the list box's currently selected item.
SelectedIndices Gets a collection that contains the indices of all selected items in the list
box.
SelectedItem Gets/sets the selected item in the list box.
You can add items to a list box at either design time or at run time; the first item will have
index 0, the next index 1, and so on in the list box. At design time, you can use the Items
property, which is a very handy array of the items in the list box, and at run time, you can use
both the Items property and the Add (formerly AddItem) method.
How do you keep track of the total number of items in a list box? You use the Items.Count
property; that is, if you loop over the items in the control, you'll use Items.Count as the
maximum value to loop to. You can access items individually in a list box by index using the
Items property, like this: strText = ListBox1.Items(5).
SelectedIndexChanged
You can use the SelectedIndexChanged event, which is the default event for list boxes, to
handle the case where the selected item changes in a list box. In the ListBoxes example
which item was clicked in the list box using this event (adding one to the item's index, which
is 0-based), like this:
You can use the RemoveAt method to delete items from a list box. To remove the item at
index 5, you'd use this code:
ListBox1.Items.RemoveAt(5);
Here's how you'd remove the currently selected item with RemoveAt:
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex);
You also can use the Remove method to remove a specific object from a list box. Here's how
I'd remove the currently selected item with Remove:
ListBox1.Items.Remove(ListBox1.SelectedItem);
You also can remove items by passing the corresponding object to Remove. For example, if
I've filled a list box with String objects, I can remove the item "Item 1" this way:
combo boxes combine a text box and a list box (which is why they're called combo boxes). In
fact, combo boxes are derived from the ListBox class:
Object
MarshalByRefObject
Component
Control
ListControl
ComboBox
You can find the more notable public properties of the ComboBox class in Table 7.7, the
more notable methods in Table 7.8, and the more notable events in Table 7.9. Note that as
with other Windows forms controls, I am not listing the notable properties, methods, and
events ComboBox inherits from the Control class, such as the Click event—you can see all
that in Chapter 5, Tables 5.1, 5.2, and 5.3.
There is only one kind of combo box, but there are really three types. You select which type
you want with the combo box's DropDownStyle (formerly Style) property.
settings for the combo box DropDownStyle property- these are members of the
ComboBoxStyle enumeration:
DropDown (the default)-Includes a drop-down list and a text box. The user can select
from the list or type in the text box.
Simple-Includes a text box and a list, which doesn't drop down. The user can select
from the list or type in the text box. The size of a simple combo box includes both the
edit and list portions. By default, a simple combo box is sized so that none of the list
is displayed. Increase the Height property to display more of the list.
DropDownList-This style allows selection only from the drop-down list. This is a
good one to keep in mind when you want to restrict the user's input, but if you want to
use this one, you also should consider simple list boxes.
A combo box is a combination of a text box and a list box, so at design time, you can
change the text in the text box part by changing the Text property.
As with list boxes, you also can use the Items.Insert,Items.Add, and Items.AddRange
methods to add items to the list part of a combo box.
Combo boxes are combinations of text boxes and list boxes, and that combination means that
there are two sets of input events: TextChanged events when the user types into the text box,
and SelectedIndexChanged,Click, or DoubleClick when the user uses the list box part of
the combo box. Note that, unlike standard list boxes, you cannot make multiple selections in
a combo box's list box.
TextChanged Events
When the user changes the text in a combo box, a TextChanged event occurs, just as it does
when the user types in a standard text box. You can read the new text in the text box with the
Text property; for example, here's how we display the new text in the combo box every time
the user changes that text by typing:
SelectedIndexChanged Events
When the selection changes in a combo box, a SelectionChanged event happens, and you
can use the SelectedIndex and SelectedItem properties to get the index of the newly selected
item and the item itself. Here's some code from the ComboBoxes example on the CD-ROM
that reports the new selection when the user makes a new selection in the combo box:
Click Events
You also can get Click events when the user makes a selection in the list box using the
mouse.
You might expect that where there are Click events there are DoubleClick events.
First of all we need to make a database file for our project. Here I'm using an OLEDB
connection so I create my database in Microsoft Access; see:
Enter the data and field names into the database like in this table:
If you want to start a new project, please use the following instructions.
1. First start Visual Studio then click on "New Project" in the Sart Page, as in the following:
2. Select a Destination folder path for the new project and name.
3. Now we connect our database to the project. For that please review the following screen.
Click On Server Explorer [Mostly placed on left hand side. or you can access it from here.
{View -> Server Explorer} or press Ctrl+Alt+S]
Select your Data Source then click "Continue" [Here we use OLEDB so I select "Microsoft
Access Database File", but you can select something else as per your need.]
Now the screen for Add Connection appears. Here we select our database file from where we
save it.
Select your database file from your computer drive and click on "Open", as in:
|
Now to check whether our connection is successful or not. Click On "Test Connection". Now
click on "OK" to close the test connection message box.
After that click on "Add Connection's 'OK' button for complete our database add operation.".
Now see in Server Explorer. Here you will see the database and its fields in "Data
Connection" as in the following:
Now right-click on the database name (i.e. data.accdb) and select Properties (Alt+Enter).
Its opens a "Properties" sidebar. Click on the Connection String and copy that. We need it for
out connection coding.
Add References
using System.Data.OleDb;
Now for the button's Click Event (for that double-click on the "OK" button) place this code:
}
You can also perform "Insert", "Delete", "Update" etc. operations using this code. For that
just change the query and replace "ExecuteNonQuery()" with "ExecuteScaler()".
You usually add navigation controls, such as the buttons at the bottom of the DataBinding, to let
the user move from record to record. When the user clicks the > button, for example, the bound
data from the next field is displayed in the text box, so the name displayed in the text box
changes from the first author's last name, White, to the last name of the next author, Green. The
>> button moves to the last record, as you'd expect; the << button moves to the first record, and
so on. And note that the code also displays the user's current location in a label control at the
bottom.
Data binding provides a way for developers to create a read/write link between the controls on a
form and the data in their application (their data model). Classically, data binding was used
within applications to take advantage of data stored in databases. Windows Forms data binding
allows you to access data from databases as well as data in other structures, such
as arrays and collections.
Binding Context
Each Windows Form has at least one BindingContext object that manages
the CurrencyManager objects for the form. For each data source on a Windows Form, there
is a single CurrencyManager object. Because there may be multiple data sources associated
with a Windows Form, the BindingContext object enables you to retrieve any particular
CurrencyManager object associated with a data source.
Example
For example if you add a TextBox control to a form and bind it to a column of a table (e.g.
"Customers.FirstName") in a dataset (e.g. "dsCust"), the control communicates with the
BindingContext object for that form. The BindingContext object, in turn, talks to the specific
CurrencyManager object for that data association. If you queried the CurrencyManager's Position
property, it would report the current record for that TextBox control's binding. In the example
below, a TextBox control is bound to the FirstName column of a Customers table on
the dsCust dataset through the BindingContext object for the form it is on.
CurrencyManager
The CurrencyManager is used to keep data-bound controls synchronized with each other
(showing data from the same record). The CurrencyManager object does this by managing a
collection of the bound data supplied by a data source. For each data source associated with a
Windows Form, the form maintains at least one CurrencyManager. Because there may be more
than one data source associated with a form, the BindingContext object manages all of the
CurrencyManager objects for any particular form. More broadly, all container controls have at
least one BindingContext object to manage their CurrencyManagers.
An important property of the CurrencyManager is the Position property. Currency is a term used
to refer to the currentness of position within a data structure. You can use the Position property of
the CurrencyManager class to determine the current position of all controls bound to the same
CurrencyManager.
For example, imagine a collection consisting of two columns called "ContactName" and "Phone".
Two TextBox controls are bound to the same data source. When the Position property of the
common CurrencyManager is set to the fourth position within that list (corresponding to the fifth
name, because it is zero-based), both controls display the appropriate values (the fifth
"ContactName" and the fifth "Phone") for that position in the data source.
Example
For example the Position property of the CurrencyManager is often manipulated in a Next / Prev
Navigation Button.
}
}
To set the current record bound to the various controls in a form, you use the form's
BindingContext property (see "Using the BindingContext Class" in this chapter), which is
inherited from the Control class. The binding context sets the location in various data sources
that are bound in the form. To see how to use the binding context, I'll start by seeing how the
code displays the current location in the authors table.
You use the BindingContext class to access the data bindings in a control, including a form. Here
is the inheritance hierarchy of this class:
Object
BindingContext
Each object that inherits from the Control class can have a single Binding Context object. Using
this object gives you access to the data bindings in a form, which allows you to set the current
record displayed in simple-bound controls, using the Position property.
You can find the more notable public properties of BindingContext objects in Table 21.9, and
their more notable methods in Table 21.10. (This class has no non-inherited events.)
Navigating in Datasets
we can use a BindingContext (see the previous topic) object's Position property to move through
a dataset, setting the current record that simple-bound controls are bound to and display. In the
DataBinding example on the CD-ROM, I used this property to display the current location in a
dataset and to navigate through the dataset.
In the DataBinding example, I displayed the current location in a label, like this:
To move to the next record in the DataBinding example, I increment the Position property (this
property won't increment if we're at the end of the dataset):
Me.BindingContext(DataSet11, "authors").Position = _
Me.BindingContext(DataSet11, "authors").Position + 1
Moving to the Previous Record
To move to the previous record in the DataBinding example, I decrement the Position property
(this property won't decrement if we're at the beginning of the dataset):
To move to the first record in the DataBinding example, I set the Position property to 0:
this.BindingContext(DataSet11, "authors").Position = 0;
Moving to the Last Record
To move to the last record in the DataBinding example, I only have to set the Position property to
the total count of the records in the dataset minus one:
This usually means binding controls to data from databases; You also can now bind any property
of any control to a data source.
Navigation—When you bind a data source to controls, you can display the data in that source and
allow the user to move through that data, record by record. This is a great way to give the user
easy access to your data.
Data Entry—Using data binding, you can create data-entry forms, letting the user enter data that
is then sent to a database. The user can enter data using, for example, text boxes, radio buttons,
list boxes, drop-down list boxes, and checkboxes, making it easy to work with what otherwise
might be a complex database system.
Master/Detail Applications—When you have a data relation that ties tables together, binding that
data to controls can let you make use of that relation. For example, you may display the names of
publishers from the publishers table in the pubs database in a combo box, and, when the user
selects one of the publishers, the titles they've published, from the table named titles, come up in
a data grid. (The connection between the two tables is supported with the pub_id field; see
"Using Master/Detail Relationships and Data Relation Objects" in this chapter for an example of
this at work.) This is called a master/detail, or parent/child, relation between the tables.
Data Lookups This is supported with the ValueMember and DisplayMember properties that
controls such as list boxes support;
simple binding lets you display one data element, such as a field's value from a data table, in a
control.
You also can bind to any property of a control, and to do that, click the ellipsis button that appears
when you click the (Advanced) entry in the (DataBindings) property, opening the Advanced
Data Binding dialog you see in Figure 21.2.
You also can perform simple binding in code, using a control's DataBindings property
complex data binding allows a control to bind to more than one data element, such as an entire
table in a database, at the same time. DataGrid1.DataSource = DataSet11
DataGrid1.DataMember = "authors"
You also can use the built-in data grid method named SetDataBinding for this (data grids are the
only controls that have this method):
DataGrid1.SetDataBinding(dsDataSet, "authors")
Text boxes are simple data-binding controls. Here are the commonly bound properties displayed
when you expand the (DataBindings) property:
Tag
Text
Binding Buttons
Buttons are simple data-binding controls. Here are the commonly bound properties displayed when
you expand the (DataBindings) property:
Tag
Text
Binding Checkboxes
Checkboxes are simple data-binding controls. Here are the commonly bound properties displayed
when you expand the (DataBindings) property:
CheckAlign
Checked
CheckState
Tag
Text
Radio buttons are simple data-binding controls. Here are the commonly bound properties displayed
when you expand the (DataBindings) property:
CheckAlign
Tag
Text
Combo boxes are complex data-binding controls. Here are the properties you use to bind this
control to a data source (for more on these properties, see the In Depth section of this chapter):
DataSource
DisplayMember
ValueMember
List boxes are complex data-binding controls. Here are the properties you use to bind this control
to a data source (for more on these properties, see the In Depth section of this chapter):
DataSource
DisplayMember
ValueMember
We've already put the data grid control to work in the previous chapter, and in the DataBinding
example in this chapter. This control displays a data table all at once in a scrollable grid format
and is supported by the DataGrid class. Here is the inheritance hierarchy of this class:
Object
MarshalByRefObject
Component
Control
DataGrid
You also can display hierarchical datasets in data grids. In a hierarchical dataset, fields themselves
can display Web-like links to child tables. You can click a link to navigate to the child table.
When a child table is displayed, a back button appears in the caption that can be clicked to
navigate back to the parent table.
You can find the more notable public properties of DataGrid objects in Table 21.6, their more
notable methods in Table 21.7, and the more notable events in Table 21.8. Note that as with other
Windows controls, I am not listing the notable properties, methods, and events ListBox inherits
from the Control class, such as the Click event—you can see all that in Chapter 5, Tables 5.1,
5.2, and 5.3.
Now that we're creating data-entry forms, it's useful to know that you can validate the data the user
enters into controls. If a control contains data that you think invalid, you can use an error
provider (see the previous topic) to indicate what the error is. Here are the control events and
properties you use in data validation:
Validating Event— Occurs when the control is validating, which happens when the control
loses the focus (if the control's CausesValidation property is True). Place code to check the
control's data here, and throw an exception if there's a problem. You can set an error provider's
message here.
Validated Event— Occurs when the control is done validating. This event occurs if no
exception was thrown in the Validating event. You can clear an error provider's message here.
CausesValidation Property— True if entering the control causes validation to be performed on
other controls requiring validation when this control gets the focus; otherwise, False. The default
is True.
You can see how this works in the Validation example on the CD-ROM. In that example, I use two
text boxes and code that insists that the user enter data into each text box. If the user hasn't
entered data into a text box and clicks the other text box (making the current text box lose the
focus), the error provider in this example displays an icon with a tool tip indicating what the error
was, as you see in Figure 21.17.
To follow along in this example, add two text boxes to a project's main form, and make sure their
CausesValidation property is set to True (this is the default), which means that when either text
box receives the focus, it'll cause all the other controls' Validating events to occur. Also, add an
error provider object, ErrorProvider1, from the toolbox.
In the Validating event for TextBox1, I check to see if the user has entered data into that text box,
and if not, use the SetError method of the error provider to display an error provider icon next to
the text box, with a message, "Please enter a value", which will be displayed in the icon's tool tip,
as you see in Figure 21.17. I also throw an exception so Visual Basic knows the data in the
control did not validate properly:
If the text box data did not validate, the icon and tool tip appear, as you see in Figure 21.17. On the
other hand, if the data does validate properly, no exception is thrown by the code in the
Validating event, and the Validated event for the control occurs. I'll clear the error provider's
error in this event's handler in case the user has corrected a data-entry error and the error icon is
showing (this will hide the error icon if it's showing):
And I'll also add error handling for the second text box, TextBox2, in the same way:
In the add new project dialog box select "Setup and Deployment" from other project types and then
select Setup Project.
In the setup project file system editor window, right-click on the Application folder then select "Add"
> "Project Output".
Now select primary output from the next dialog box and click on OK.
Right-click on the user's Desktop and create a shortcut to primary output in the application folder.
Build the project by right-clicking on the setup project name and run the setup.
You can publish a ClickOnce application in three various ways: from a Web page, from a network file
share, or from media such as a CD-ROM. A ClickOnce application can be installed on an end user's
computer and run locally even when the computer is offline, or it can be run in an online-only mode
without permanently installing anything on the end user's computer.
Open the Visual Studio 2008 IDE and create a new Windows application.
Publish Location
be required.)
If you select 'The application is available online only', each time it is run then it will be run
from the published location and no start menu icon will be created.
But by selecting 'The application is available offline as well', A shortcut on the Start menu
will be created for the application and it will enable the application to be run when the user is
disconnected from the network.
Publish Version
Here you should state the publish version (not the application version). And if you check
'automatically increment revision with each publish' then that will ensure that the revision
number will be incremented automatically each time you publish your application.
Application Files
sometimes it is necessary to publish other files than the application. So this is where you state
which ones to include or exclude from the deployment.
Prerequisites
You can create a setup file to install the prerequisites, that are required by your application to
function correctly. And all required prerequisites are selected automatically. But if you want,
you can either add or remove them from your prerequisites setup.
Updates
In this window, you should define how your application should be updated. Check 'The
application should check for updates' and choose whether it should be updated before or after
the application starts. If you choose to update it after running the application then you can
mention whether you want to check each time it runs or can mention a time period, that it
should check. But it is always advisable to check before application starts, so users will get
And specify a minimum required version, so that the end user will get the specified version of
the application, if they have an older version installed on their PC.
If the updating location is other than the publish location then please provide the path.
Save the settings and go to the form designer and add a label to the form.
Menu bars provide a good starting point for our discussion in this part of the
book.
Menus provide a convenient way to group similar or related commands in one
place.
Most users are familiar with the menu bar concept and expect standard menus
such as
File, Edit, and Help to appear in their applications. Even novice computer users
quickly
learn that clicking a menu on the menu bar displays a dropdown list of
commands.
Menus became popular on Windows applications in the late 1980s, following
their success on the Apple Macintosh. Prior to menus, users had to cope with a
wide
array of interfaces offered by desktop applications. The function keys still found
at the
top of computer keyboards were developed in part as a standard way to access
common
functions in an application, and some programs even went so far as to provide a
plastic
template that sat on top of these function keys to help users remember the
available
commands.
Perhaps because of this history, many developers take the usefulness and
popularity
of menus for granted and do not spend sufficient time laying out a consistent,
usable interface for their application. While graphical elements such as menus,
toolbars,
and other constructs make applications much more friendly, this is not an excuse
to ignore good user design and rely on customers to become “experienced” to
make
effective use of the interface.
70 CHAPTER 3 MENUS
Well, if that little lecture doesn’t get your creative juices flowing, then nothing
will. Back in .NET-land, Visual Studio .NET provides a rather intuitive interface for
the construction of menus that does away with some of the clunkiness found in
earlier
Windows development environments from Microsoft. No more dealing with
menus
in one place, the application in another place, and the menu handlers in a third
place.
This chapter will cover the following aspects of menu creation and handling:
• Defining different types of menus
• Creating and modifying menus and menu items
• Handling menu events
• Handling multiple menus from a single event handler
• Cloning (as in copying) menu items from one menu to another
The examples in this chapter assume you have the code for MyPhotos version
2.4
available, as developed with Visual Studio .NET in the previous chapter. You can
use
this code with or without Visual Studio as a starting point for the tasks covered
here.
If you did not work through chapter 2, download the project from the book’s web
site
at http://www.manning.com/eebrown. Follow the links and instructions on the
page
to retrieve version 2.4 of the application.
3.1 THE NATURE OF MENUS
Before we add some menus to our application, we should talk about the different
kinds of menu structures and the classes that support them in the .NET
Framework.
The traditional menu bar, sometimes called the main menu or an anchored
menu, is a
set of menus shown horizontally across the top of most applications. The menus
in a
typical menu bar display a dropdown list
of commands when they are activated
with the mouse or by a keyboard accelerator.
Figure 3.1 shows an example of a
menu bar containing a File, View, and
Help menu. The View menu is exposed,
and a submenu of the Image menu item
is displayed as well.
Another type of menu is a context
menu, also called a popup menu or shortcut
menu. A context menu is a menu that
appears in a particular situation, or context.
Typically, a context menu contains
a set of commands or menus related to a
specific graphical element of the application.
Such menus appear throughout the
Windows environment at the right-click
Figure 3.1 A traditional menu bar provides a
set of menus across the top of an application
THE NATURE OF MENUS 71
of the mouse. For example, right-click the Windows desktop, any program icon
on
your screen, or even the Windows start menu, and a context menu will pop up
with
a set of commands related to the
desktop display, the program, or
the start menu, respectively.
Component class.
Public Properties
Handle Gets the window handle for the menu. Used as a
back door to special operations not supported by
the framework.
IsParent Gets whether this menu contains any MenuItem
objects.
MdiListItem Gets the MenuItem, if any, that will display the
list of MDI child forms currently open in the
application.
MenuItems Gets the MenuItemCollection object that
holds the list of MenuItem objects attached to
this menu, or null if no items are attached.
Public Methods
GetContextMenu Returns the ContextMenu object that contains
this menu, or null.
GetMainMenu Returns the MainMenu object that contains this
menu, or null.
MergeMenu Merges a given Menu object into the current
menu.
Public Events
Disposed (inherited
from Component)
Occurs when the component is disposed, such
as when the Dispose method is called for the
component.
THE NATURE OF MENUS 73
even internal types such as int and char, implicitly derive from the object class.1
In the .NET Framework, this class is equivalent to the Object class. We will
discuss
this class in more detail in chapter 5.
The MarshalByRefObject class is an object that must be marshaled by reference.
Marshaling is a method of passing an item from one context so that it can be
understood in another context. A typical use for marshaling is in remote
procedure
calls between two different machines, where each parameter of a function call
must be
converted into a common format (that is, marshaled) on the sending machine so
that
it may be interpreted on the receiving machine. In the .NET world, Windows
controls
are MarshalByRefObject objects since they are only valid in the process that
creates
them, and can be used outside this process only by reference. 2
The Component class is the base implementation of the IComponent interface.
A component is an object that can exist within a container, and allows cleanup of
nonmemory
resources via the Dispose method. This class supports the IDisposable
interface as well the IComponent interface. We’ll cover interfaces in chapter 5, so
don’t get caught up in the terminology here. Since graphical controls exist within
a
Form window or other container control, all Windows Forms controls ultimately
derive from this class.
3.1.3 DERIVED CLASSES
The .NET Framework derives three menu classes from the abstract Menu to
support
menu bars, context menus, and the menu items they contain.
• The MainMenu class represents a main menu for an application. MainMenu
objects contain a collection of MenuItem objects to display in the menu bar.
• The ContextMenu class represents a context menu associated with a specific
for your own program. Note that this and most other tables at the beginning of a
section
change the version number in the program as a way to track our progress
throughout the book and as a link to the online code at the book’s web site. If
you
recall, the version number is modified in the AssemblyInfo.cs file of the project.
Before we add the menu, we need to remove the existing Load button from the
form.
Figure 3.4 Notice in this File menu how
the Load item displays Ctrl+L as its keyboard
shortcut.
MENU BARS 75
Set the version number of the application to 3.2.
With the Load button gone, our way is now clear to move this functionality into a
menu bar. We continue the above steps and add a menu bar to our form.
REMOVE THE LOAD BUTTON
Action Result
1 Remove the Load button from the
form.
Visual Studio automatically removes all generated code
related to the button from the InitializeComponent
method of the MainForm.cs file.
Note: When a control is deleted, the declaration of
any event handlers are removed, but the actual event
handling code, in this case our btnLoad_Click
method, must be removed manually.
We will remove this code later in the chapter.
2 Display the properties for the
PictureBox control.
The property values for this control are displayed.
3 Set the value of the Dock
property to Fill.
Clicking the center button as shown in
the graphic sets the value of the Dock
property to Fill, so that the
PictureBox control takes up the entire
display window of the form.
Note: When the Dock property is set to a value
other than None, the Anchor property is automatically
set to its default value of Top and Left.
How-to
a. Display the MainForm.cs
[Design] window.
b. Right-click the Load button.
c. Select the Delete option.
Alternately
Simply select the button and hit
the Delete key.
How-to
a. Right-click on the control.
b. Select Properties.
Alternately
Click the control and use the
keyboard shortcut Alt-Enter.
How-to
a. Locate the Dock property.
b. Display the dropdown window
for this property.
c. Click the center button.
CREATE THE MAIN MENU BAR
4 Display the Toolbox window. A list of available controls is displayed.
How-to
a. Click the View menu in Visual
Studio.
b. Select the Toolbox option.
Alternately
Click the wrench and hammer
icon on the left side of Visual
Studio.
76 CHAPTER 3 MENUS
Let’s take a look at the source code generated by these actions in the
MainForm.cs
window. If this window is not shown, right-click the mainMenu1 object and select
View Code. You will note that the Windows Forms Designer has added the
mainMenu1 variable to the MainForm class.
private System.Windows.Forms.MainMenu mainMenu1;
The InitializeComponent method we discussed in chapter 2 initializes this
variable
and attaches it to the form. An object for this variable is created using the new
keyword. As we mentioned in part 1, the this keyword refers to the current class
instance, just as it does in C++.
this.mainMenu1 = new System.Windows.Forms.MainMenu();
At the end of the method, the MainMenu object is attached to the form using the
Form.Menu property. This property sets or retrieves a MainMenu object to appear as
the main menu bar for the application, and can be used to swap in and out
different
menu bars to customize how the menu looks for specific situations. We will only
use
a single MainMenu object in this chapter. See .NET Table 3.2 for additional details
on the MainMenu class.
this.Menu = this.mainMenu1;
Also notice in the code how the Anchor property setting for the PictureBox control
has been replaced by the Dock property.
this.pbxPhoto.Dock = System.Windows.Forms.DockStyle.Fill;
5 Drag a MainMenu object from the
Toolbox onto your form.
A MainMenu object called mainMenu1 is added to your
form. This object is displayed in a new area called the
component tray below the form where objects appear
that may not have a physical presence in the window.
Such objects include timers, database connections, and
main menus.
Note: An example of the component tray showing
the mainMenu1 object appears later in this
chapter in figure 3.9, on page 99.
CREATE THE MAIN MENU BAR (continued)
MENU BARS 77
3.2.2 ADDING THE FILE MENU
With a MainMenu on our form to act as the menu bar, we can now add the menus
that should appear. Each menu is created using the MenuItem class. In this
section
we will create the top-level File menu only. In the next section we will create the
dropdown menu that appears when the user clicks on this menu.
.NET Table 3.2 MainMenu class
The MainMenu class is a container class that holds a collection of MenuItem objects to appear
as a menu bar on a Windows form. This class is part of the System.Windows.Forms
namespace, and inherits from the Menu class. A main menu is assigned to a specific window
using the Menu property in the Form class. See the .NET Table 3.1 on page 72 for a list of
members inherited from Menu.
Public Properties
RightToLeft Gets or sets whether text displayed by the menu
should use a right-to-left alignment. This is useful
when displaying a language such as Hebrew or
Arabic which reads from right to left.
Public Methods
CloneMenu Returns a new MainMenu as a duplicate of the
current menu.
GetForm Returns the Form object that contains this menu, or
null if this menu is not contained by a Form.
CREATE THE FILE MENU
Action Result
1 Edit the menu bar in the
MainMenu.cs [Design] window.
An empty menu bar appears at the top of the form. The
property values:
The modified properties are displayed in the Properties
window.
Note: The Shortcut property defines a keyboard shortcut,
in this case Ctrl+L, that immediately invokes the
menu as if it were clicked, without actually displaying the
menu.
The access key Alt+L for this menu can be used to
select this menu from the keyboard after the File menu
has been displayed.
3 Add a menu separator after
the Load menu.
How-to
Enter a dash character ‘–’
as the next menu item.
A menu separator is added to the dropdown menu.
Note: By definition, a menu separator in .NET is a Menu-
Item with its Text property set to a single dash.
We will leave the (Name) of the separator as the
default value.
How-to
a. Make sure the designer
window is displayed.
b. Click on the File menu.
c. Type in “&Load” below
the File menu where it
says Type Here
Settings
Property Value
(Name) menuLoad
Shortcut CtrlL
Text &Load
80 CHAPTER 3 MENUS
As you might expect, the code generated for the MainForm.cs file uses MenuItem
objects to add this dropdown list to the File menu, with the objects initialized in
the
InitializeComponent method. The relevant code from the source file is shown
here.
private System.Windows.Forms.MenuItem menuLoad;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuExit;
. . .
private void InitializeComponent()
{
. . .
this.menuLoad = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuExit = new System.Windows.Forms.MenuItem();
. . .
//
// menuFile
//
this.menuFile.Index = 0;
this.menuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[]{
this.menuLoad,
this.menuItem1,
this.menuExit});
this.menuFile.Text = "&File";
//
// menuLoad
//
this.menuLoad.Index = 0;
this.menuLoad.Shortcut = System.Windows.Forms.Shortcut.CtrlL;
this.menuLoad.Text = "&Load";
//
// menuItem1
//
4 Finally, add the Exit menu
item.
The File menu is now complete.
Note: Of course, the Windows keyboard shortcut Alt-F4
can always be used to close the application. There is no
need to add this keystroke to our menu as it is imposed
by the operating system.
b Create File
drop-down
menu
Define c
keyboard
shortcut
MENU BARS 81
this.menuItem1.Index = 1;
this.menuItem1.Text = "-";
//
// menuExit
//
this.menuExit.Index = 2;
this.menuExit.Text = "E&xit";
. . .
}
Some aspects of this code are worth highlighting:
b As we saw for our main menu, the items to appear under the File menu are
added by
constructing an array of the desired MenuItem objects and assigning them to the
menuFile.MenuItems property. Note that this array does not establish the order in
which these items will appear. The display order is established by the menu
index
assigned to each object.
c The Ctrl+L shortcut for the Load menu is defined through the use of the
System.
Windows.Forms.Shortcut enumeration.
d This line creates our separator menuItem1 by setting its Text property to a dash
(-).
e The Index property defines the zero-based position of the menu item within its
parent
menu. This position establishes the order in which menu items are displayed. In
our code, the dropdown list for the File menu should display the Load menu, then
a
separator, and then the Exit menu. This is done by setting the Index property for
these objects to 0, 1, and 2, respectively.
Our code uses a few of the properties provided by the MenuItem class. Other
properties
will be used as we progress through this and subsequent chapters. An overview
of
the MenuItem class appears in .NET Table 3.3.
If you wish to see the application so far, compile and run the code to view the
File menu. You will notice that the menu bar contains only a single item, which is
perhaps
a bit boring. We do not want a boring application, so we will double the number
of menus in our next section.
d
Create menu
separator
e Set menu index
82 CHAPTER 3 MENUS
.
The MenuItem class represents a menu within a MainMenu or ContextMenu object, or a submenu
of another MenuItem object. MenuItem objects are displayed to the user, while Main-
Menu and ContextMenu objects simply establish a container in which MenuItem objects can
appear. The MenuItem class is part of the System.Windows.Forms namespace, and inherits
from the Menu class. See .NET Table 3.1 on page 72 for a list of members inherited from this
base class.
Public Properties
Checked Gets or sets whether a check mark appears next to the
text of the menu item.
Enabled Gets or sets whether the menu item is enabled. A
disabled menu is displayed in a gray color, cannot be
selected, and does not display any child menu items.
Index Gets or sets the position of the menu item within its
parent menu.
MergeOrder Gets or sets the value of the relative position for the
menu when it is merged with another.
OwnerDraw Gets or sets whether Windows draws the menu
(false) or the application will draw the item (true).
Used to create custom menus.
Parent Gets the Menu object that is the parent of this menu.
RadioCheck If Checked is true, gets or sets whether to display a
radio button next to the menu instead of a checkmark.
Shortcut Gets or sets the shortcut key for this menu item.
ShowShortcut Gets or sets whether to display the Shortcut setting
when displaying the menu.
Text Gets or sets the text to display for the menu. The
character following an ampersand (&) is used as an
access key.
Visible Gets or sets whether to display the menu item.
Public Methods
CloneMenu Creates a copy of the MenuItem.
MergeMenu Merges this menu with another MenuItem.
PerformClick Generates a Click event for this item.
PerformSelect Generates a Select event for this item.
Public Events
Click Occurs when the user clicks the menu or accesses it
via an accelerator or shortcut key.
DrawItem Occurs when the OwnerDraw property is true and a
request is made to draw the menu item.
MeasureItem Occurs when the size of the menu item is required
before drawing it.
Popup Occurs before the menu item displays its list of child
menus.
Select Occurs when the menu is highlighted using the mouse
or keyboard.
MENU BARS 83
3.2.4 ADDING A VIEW MENU
We have seen how to add simple menu items and menu separators, so here we
will do
something different. Let’s add a menu with a submenu to see how the displayed
image
should appear in the window. This will give us an opportunity to cover checked
menus
as well. Figure 3.5 shows the View menu we will create as it appears in Visual
Studio.
The View menu and its single menu item Image are created similar to the
manner in
which the File menu was previously created.
Figure 3.5
Menus in Windows Forms Designer are
similar to their appearance in an application,
with the addition of a “Type Here”
wherever a new menu item can be added.
CREATE THE VIEW MENU
Action Result
1 Add a top-level View menu
to the right of our existing
File menu.
A new MenuItem object called menuView is created in the
the shortcut for the Load menu is displayed within the menu. Try setting
the ShowShortcut property for this menu to false in order to prevent
this shortcut from appearing on the menu. Note that the keyboard shortcut
still works, the user is just not told about it in the menu bar.
Sit back for a moment and think about what we have done here. If you have
used
Visual C++ with MFC, you should realize that the secret macros and magic
interface
files required by this environment are gone. In their place are well-designed
objects
that can quickly and easily be used to create arbitrarily complex menu
structures.
If you have been following the examples with Visual Studio .NET, also realize
that you have not written any code thus far. This