Tutorial VisualStudio2008
Tutorial VisualStudio2008
2] Select C# for the language. Select the Windows Application template. The Faculty form is going to be one of
several forms that I wish to create for a Trinity University database application; I am naming the Application TU; it
shall reside at the root of drive C.
Un-Check the Create directory for solution. Using the mouse, select/push the OK button. (See Below!)
3] All of the files and folders, created by Visual Studio, can be seen in directory C:\TU. (See Below!)
Compile & Execute The Windows Application From Within The Visual Studio Application Development
Environment
1] I normally do not use the Debug environment unless I am having problems. I most often launch the application
without the debugging. Using the mouse, hold down the Debug Menu --> Select Start Without Debugging. (See
Below!) You can also do this by holding down the Ctrl and F5 Keys.
2] Since we have added nothing to the form, it is pretty plain, but it does execute.
Close Form1.
1] There are literally hundreds of customizations that you can do with Visual Studio. Since I use Start Without
Debugging a lot, I like to add it to my Visual Studio Menus. Using the mouse, hold down the Tools Menu --> Select
Customize. (See Below!)
2] Select the Commands Tab. Select the Debug Category. Scroll down and select the Start Without Debugging
Command. Using the mouse grab hold of the Start Without Debugging icon
and drag it to the desired location on the Visual Studio Tool Bar; I have placed it to the right of the Help Menu choice.
(See Below!)
Just for the sake of illustration, I have added two copies of this quick launch to the Visual Studio. (See Below!)
icons.
Rename A Form
1] An application will often have many forms. This form shall contain information about Faculty; it should be named
appropriately. Using the mouse, right mouse click on Form1.cs and select Rename. (See Below!) Rename the form
Faculty.cs. Do not forget the .cs extension!
2] This may take a moment or two. It will make numerous changes to the classes.
1] Among the things changed with the renaming was Program.cs. Note that Program Main( ) concludes by running
Application.Run(new Faculty()); it launches the form we just created.
1] Each and every form should have a great title. You can change any of the form properties by right mouse clicking
on any portion of the form that does not contain an object, such as a button, label, text box, combo box, etc. -->
Select Properties. (See Below!)
2] The Properties Panel will enable us to change many of the form properties. Select the Text Property. Each form
should have a clear, descriptive title. Change the Text Property of the form to Faculty Application Written By
(????!), <-- Replace ???? with Your Name! (See Below!)
to
3] Save the application and launch the form.
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) Select the BackColor Property.
Press the color selector drop-down control
and select a color pallet from Custom, Web, & System. Using the mouse, I have selected a dark blue from the Custom
color pallet. (See Below!)
About The Form's Default Font Face, Style, Size & Color
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
2] In the screen capture below, a label is dragged from the toolbox to the form.
3] When you look at the current Font Property below, you will notice that the Microsoft Sans Serif (8.25 pt) font is
defined for our form. Label1 uses this font in the screen capture above. When you look at the ForeColor Property
below, you will notice that the Black ControlText is defined. Label1 uses this black font color in the screen capture
above.
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
2] It is indeed the case that you can always change the font style, size, and color, but it is often more efficient to
make the desired settings the default. Suppose we wish to change the default form Font to 12 Point Ariel. Select the
Font Property. Press font configuration control
3] I wish to use the Ariel Font, Bold Style, and 12 Point Size. Using the mouse, select/push the OK button. (See
Below!)
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
2]t is indeed the case that you can always change the font style, size, and color, but it is often more efficient to make
the desired settings the default. Suppose we wish to change the default form Font Color to White. Select the
ForeColor Property. Press the color selector drop-down control
and select White from the Custom Color Pallet. (See Below!)
Revisit The Form's Default Font Face, Style, Size & Color
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
2] A Label is once more dragged from the Toolbox to our form. Note that the font is 12 pt, Bold, Ariel, and White in
color. (See Below!)
1] Rather than use the Windows Default Location when this form is launched, suppose we wish to place the form 20
pixels down and across from the upper left corner of the screen.
2] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
3] This is a two step process. The first step is to change the StartPosition Property. There are several options; select
the Manual starting position. (See Below!)
4] If the form were launched now, it would be in the upper left corner of the screen because the Location values are
0,0. Change Location to 20, 20 to set the Manual Starting Position for our Faculty Form.
Close the Faculty form. The StartingPosition Property can also be used to center the from.
AutoScroll
1] Return to the properties panel for the form (right mouse clicking on any portion of the form that does not contain
an object, such as a button, label, text box, combo box, etc. --> Select Properties) The default font for the form is
used whenever you drag font-oriented controls to the form. Font oriented controls include Labels, Text Boxes, Combo
Boxes, etc. Suppose I drag a Label to our form.
2] In order to AutoScroll, the AutoScaleMode Property must be set to None.
3] Change the AutoScroll Property to True. In order to illustrate AutoScroll, there must be some objects on the form.
(See Below!)
4] When you grab the form window by the bottom right corner and begin to close the window, the scroll bars will
occur once you begin to close out some of the form objects. (See Below)
The Margin property defines the space around the control that keeps other controls a specified distance from the
control's borders.
The Padding property defines the space in the interior of a control that keeps the control's content (for example, the
value of its Text property) a specified distance from the control's borders.
The following illustration shows the Padding and Margin properties on a control.
1] The main program for the project is Program.cs. See the code below!
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TU
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Faculty());
}
}
}
2] Visual Studio GUI creates code behind the Faculty.cs form in file Faculty.Designer.cs. (See Below!)
namespace TU
{
partial class Faculty
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// Faculty
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 19F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.AutoValidate = System.Windows.Forms.AutoValidate.EnableAllowFocusChange;
this.BackColor = System.Drawing.Color.Navy;
this.ClientSize = new System.Drawing.Size(505, 188);
this.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.Location = new System.Drawing.Point(20, 20);
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "Faculty";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Faculty Application Written By Dr. Thomas E. Hicks";
1] The TU Project folder is located at c:\TU. Inside the project is a folder, called bin, that holds the binary executable.
By default, the binary executable is named like the project with an .exe extension. If you double-click on file TU.exe,
it will launch the form above without having to load Visual Studio.
Purpose
The purpose of this tutorial is to show how to configure, name, and manipulate labels and textboxes in a basic
Windows Application with Visual Studio.
Purpose
The purpose of this tutorial is to show how to create a basic Windows Application with Visual Studio.
If You Have Difficulty With This Tutorial, You Might Find These Help Prepare You For This Tutorial
I Recommend That My Students Complete The Tutorials In This Order!
Tutorial: Visual Studio 2008 Install
Tutorial: Visual Studio 2008 SP1 Install
Tutorial: Visual Studio Windows Application - Forms - Basic Forms
Project TU
1] The TU Project that is used for this tutorial is found below; place it at the root of drive C:\
TU-1.zip
Creating A Label
1] Labels are used to identify form content; They are used for prompts and to provide extraneous information on
forms. To create a label on the form, drag a Label from the Toolbox to the Faculty form. We are about to create a
Label for a prompt -> First Name. (See Below!)
1] The label is an object created on the form with the line of code:
this.label1 = new System.Windows.Forms.Label();
2] When you select the form with the mouse, you can see a box that identifies object label1. A dark background can
make this box more difficult to identify. (See Below!)
4] If you right mouse click on the label, you can drag it to the desired location on the form. Note the box that is
formed around the label as you move it.
1] Go to the properties panel for the label (right mouse clicking on the label. --> Select Properties)
(See Below!)
2] Select the Font Property. You can see that the current font is 12pt Ariel bold. Suppose we wish to change the font
to Comic Sans MS. Hold down the font selector
(See Below!)
3] Select the Comic Sans MS font - Regular style - 16 point. Using the mouse, select/push the OK button. (See
Below!)
5] You may select select and change multiple labels, using the procedure outlined above, at one time.
6] When doing multiple labels, it is often more efficient to set the Font associated with the form; thus it becomes the
default.
1] Return to the properties panel for the label (right mouse clicking on the label. --> Select Properties). Select the
ForeColor Property. You can see that the current forecolor is white. Suppose we wish to change the forecolor to
yellow. Press the color selector drop-down control
(See Below!)
and select Yellow from the Custom Color Pallet. (See Below!)
1] Return to the properties panel for the label (right mouse clicking on the label. --> Select Properties). Select the
BackColor Property. You can see that the current backcolor is navy. Suppose we wish to change the forecolor to
purple. Press the color selector drop-down control
(See Below!)
and select a purple from the Custom Color Pallet. (See Below!)
1] Return to the properties panel for the label (right mouse clicking on the label. --> Select Properties). Select the
Text Property. You can see that the current text is label1. Suppose we wish to change the text to First Name. Change
the Text Property to First Name. (See Below!)
2] Replace button1 with First Name. The label is now a prompt for the First Name. (See Below!)
4] This form still executes; try it. Note that the label object is no longer outlined. (See Below!)
Naming A Label
1] Some developers name each and every object on a form; I name almost every object, except labels. If you wish to
change one or more of the label properties with program code, it should be named; otherwise I encourage you to
consider it optional.
2] The name should contain no blanks. Suppose we wish to name the label - labFirstName.
3] Return to the properties panel for the label (right mouse clicking on the label. --> Select Properties). Select the
Name Property. You can see that the current name is label1. Change the Name Property to labFirstName. (See
Below!)
2] You can see that the label below has now been named.
Creating A Textbox
1] Textboxes are used both to display data and to enable the user to change that data. To create a textbox on the
form, drag a Label from the ToolBox to the right of the First Name prompt on the Faculty form. We are about to
create a Textbox which will enable the user to input and/or alter the FirstName. (See Below!)
1] The Textbox is an object created on the form with the line of code:
this.textBox1 = new System.Windows.Forms.TextBox();
2] When you select the form with the mouse, you can see a box with three controls helps to identify the textbox. (See
Below!)
5] By default, the Textbox control is a single line field. One of the ways that you can change the control to handle
multiple lines is to grab the top Textbox control
The multiline attribute adds six controls to the textbox (one on the top and one on the bottom and one on each
corner). You can now expand/contract from the top and bottom. You can expand/contract from any corner. (See
Below!)
Textbox Input
1] The program should execute as is. Try it. The user can enter data into the form; try it. When designing the form,
you should make the container large enough for the user to enter data. Note that Contricissia almost fills the
container.
2] Note that Johassiofati more than fills the container, but the data simply scrolls; none of it is lost, but not all of it
is visible.
1] Go to the properties panel for the Textbox (right mouse clicking on the Textbox. --> Select Properties)
Below!)
(See
2] Select the Font Property. You can see that the current font is 12pt Ariel bold. Suppose we wish to change the font
to Comic Sans MS. Hold down the font selector
(See Below!)
3] Select the Comic Sans MS font - Regular style - 16 point. Using the mouse, select/push the OK button. (See
Below!)
4] Note the font change below. They only change is really in the height of the box.
5] This change becomes much more obvious when you execute the application. (See Below!)
6] You may select select and change multiple Textboxes, using the procedure outlined above, at one time.
6] When doing multiple Textboxes, it is often more efficient to set the Font associated with the form; thus it becomes
the default.
1] Return to the properties panel for the Textbox (right mouse clicking on the Textbox. --> Select Properties). Select
the ForeColor Property. You can see that the current forecolor is the black windows text. Suppose we wish to change
the forecolor to red. Press the color selector drop-down control
(See Below!)
and select Red from the Custom Color Pallet. (See Below!)
3] Once again it is best to show this by executing the application. Try it!
1] Return to the properties panel for the Textbox (right mouse clicking on the Textbox. --> Select Properties). Select
the BackColor Property. You can see that the current backcolor is white. Suppose we wish to change the forecolor to
purple. Press the color selector drop-down control
(See Below!)
and select a purple from the Custom Color Pallet. (See Below!)
3] Once again it is best to show this by executing the application. Try it! This is not a good color combination!
Naming A Textbox
1] It is extremely important to name every Textbox.The name should contain no blanks. The names should clearly
identify the data. Suppose we wish to name the Textbox - txtFirstName.
2] Return to the properties panel for the Textbox (right mouse clicking on the Textbox. --> Select Properties). Select
the Name Property. You can see that the current name is textBox1. Change the Text Property to First Name. (See
Below!)
2] You can see that the Textbox below has now been named.
1] It is generally considered a good design practice to have one or two major columns within a form, or within the
form's containers.
2] Using the mouse, drag/select Labels labFirstName, labSpecialtyID, and labAbout;
(See Below!)
3] When creating reports, sent to printers, it is often considered a good practice to left-justtify the prompts.
4] When creating forms, it is often considered a good practice to right-justtify the prompts within their respective
columns.
5] Once they are selected, hold down the Format Menu --> Select Align --> Select Rights to align labels
labFtirstName, labSpecialtyID, and labAbout on the right.
(See Below!)
7] Once they are selected, hold down the Format Menu --> Select Align --> Select Rights to align labels
labFirstName, labSpecialtyID, and labAbout on the right.
8] When creating forms, it is often considered a good practice to left-justtify the textboxes within their respective
columns.
9] Using the mouse, drag/select Textboxes txtFirstName, txtSpecialtyID, and txtAbout; you can hold down the ctrl
key and mouse select if you like. (See Below!)
10] Once they are selected, hold down the Format Menu --> Select Align --> Select Lefts to align Textboxes
txtFirstName, txtSpecialtyID, and txtAbout; on the left.
11] While the three fields are selected, drag the collection of textboxes close, but not too close, to their respective
labels. (See Below!)
12] Using the mouse, drag/select Labels labLastName, labID, and labGender;
(See Below!)
13] Once they are selected, hold down the Format Menu --> Select Align --> Select Rights to align labels
labFirstName, labSpecialtyID, and labAbout on the left.
14] Using the mouse, drag/select Textboxes txtID, txtLastName, and txtGender; you can hold down the ctrl key and
mouse select if you like. (See Below!)
15] Once they are selected, hold down the Format Menu --> Select Align --> Select Left to align Textboxes txtID,
txtLastName, and txtGender on the left.
16] It is often considered a good practice to make the space between the prompt and data entry fields consistent on
the entire form.
17] While the three fields are selected, drag the collection of textboxes close, but not too close, to their respective
labels; try to keep this distance consistent throughout the form. (See Below!)
18] When the prompt is to the left of the data entry control (textbox, checkbox, drop-down, etc), it is often
considered a good practice to make sure that the row data is aligned well horizontally
19] Using the mouse, drag/select all of the Labels & Textboxes in the first row of the data. (See Below!)
20] Once they are selected, hold down the Format Menu --> Select Align --> Select Middles to align the first row
horizontally.
21] Using the mouse, drag/select all of the Labels & Textboxes in the second row of the data. (See Below!)
22] Once they are selected, hold down the Format Menu --> Select Align --> Select Middles to align the second row
horizontally.
23] Using the mouse, drag/select all of the Labels & Textboxes in the third row of the data. (See Below!)
24] Once they are selected, hold down the Format Menu --> Select Align --> Select Middles to align the third row
horizontally.
25] Using the mouse, drag/select all of the Labels & Textboxes in the last row of the data. (See Below!)
26] Once they are selected, hold down the Format Menu --> Select Align --> Select Middles to align the last row
horizontally.
27] Once aligned, your form should look something like the one below.
1] Specialty ID # 4 is Parallel Processing. Suppose that the majority of Faculty were specializing in Parallel
Processing.
2] Assign the value "4" to txtSpecialtyID
3] Return to the properties panel for the Textbox (right mouse clicking on the Textbox. --> Select Properties). Select
the Text Property. You can see that the current Text is blank. Change the Text Property to 4. (See Below!)
4] Although the user can certainly change the SpecialtyID, it will now be seen as 4 when the form loads.
1] During the software lifecycle, it is common to add additional information to databases and the forms that support
them.
2] Create two labels, called labSSN and labOffPhone; keep these two new labels consistent in style and font. Add
them to your form. (See Below!)
Masked Textboxes
1] We would like to have the social security number in a numeric format 000-00-0000 where the 0 represents any
numeric digit 0-9. "If you expect your user to be a total idiot, you will seldom be disappointed." Some will enter a
capital 'O' instead of a zero. Some will include dashes and others won't. Some will use a lower case 'l' instead of a
one. Some will enter only 8 digits. Others will just plain mess it all up.
2] The masked textbox both verifies the data entry and reduces the likelihood of user error.
3] Using the mouse, drag the MaskedTextBox control from the toolbox to your form. Name the field txtSSN. (See
Below!)
4] Return to the properties panel for the MaskedTextBox (right mouse clicking on the label. --> Select Properties).
Select the Mask property. At the moment, there is no mask; the user could enter any type of alpha-numeric data.
Using the mouse, select/push the
(See Below!)
5] We could make our own custom mask and assign 000-00-0000 to the mask; but since there is already a standard
Social Security Number, let's use it. (See Below!)
6] Run the form. As you can see from the mask, the field could be a bit smaller. Try entering the data; note that you
do not have to enter the dashes. It does not verify that the Social Security Number entered is indeed valid, but it will
not accept an 'l' or a '0' or any other invalid character; try it! (See Below!)
8] Add a MaskedTextBox field, called txtOffPhone, to the form. Configure it for the phone number type. (See Below!)
9] If we wanted the ID to be a four digit number with a dash in the middle, we could create a custom mask 00-00.
10] If we wanted the input mask to be two digit alpha-numeric, we could make the input mask AA.
1] Enter the following data into the txtAbout container. You can paste it in if you like.
Now is the time for all good folk to use C# for rapid prototyping and
development. This prototyping can be done for both web apps and stand alone
systems.
Welcome to Software Engineering at Trinity University's Computer Science
Department.
2] The top portion of it scrolled off. You can hit the up arrow key and see it, but this would give the user no indication
that there is additional data. Yuk! (See Below!)
3] As we look at the properties for txtAbout, you will notice that the contents of this Multiline are going to be
stored in a dynamic String Array. Using the mouse, hold down the ScrollBars and select Vertical. (See Below!)
4] Once enough data is entered to need the scroll, the control activates; this provides the user with some indication
that there is additional data. (See Below!)
RichTextbox
1] An alternative to configuring the TextBox control for txtAbout would be to drag the RichTextBox control instead. If
the back end of your data needed to preserve paragraph and text formatting, this is definitely the way to go. If not, it
is a choice.
2] You will notice that the contents of this Multiline are also going to be stored in a dynamic String Array. The
ScrollBars are automatically set. (See The Properties!) As you can see below, there is little difference in the form
appearance.
1] The main program for the project is Program.cs. See the code below!
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TU
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Faculty());
}
}
}
2] Visual Studio GUI creates code behind the Faculty.cs form in file Faculty.Designer.cs. Notice how the named
objects make it much easier to identify the various form objects! (See Below!)
namespace TU
{
partial class Faculty
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
///
///
///
///
<summary>
Required method for Designer support - do not modify
the contents of this method with the code editor.
</summary>
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ForeColor = System.Drawing.Color.White;
this.Location = new System.Drawing.Point(20, 20);
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "Faculty";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Faculty Application Written By Dr. Thomas E. Hicks";
this.Load += new System.EventHandler(this.Faculty_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private
private
private
private
private
private
private
private
private
private
private
private
private
private
private
private
System.Windows.Forms.Label labFirstName;
System.Windows.Forms.TextBox txtFirstName;
System.Windows.Forms.TextBox txtSpecialtyID;
System.Windows.Forms.Label labSpecialtyID;
System.Windows.Forms.TextBox txtLastName;
System.Windows.Forms.Label labLastName;
System.Windows.Forms.TextBox txtGender;
System.Windows.Forms.Label labGender;
System.Windows.Forms.TextBox txtID;
System.Windows.Forms.Label labID;
System.Windows.Forms.TextBox txtAbout;
System.Windows.Forms.Label labAbout;
System.Windows.Forms.Label labOffPhone;
System.Windows.Forms.Label labSSN;
System.Windows.Forms.MaskedTextBox txtSSN;
System.Windows.Forms.MaskedTextBox txtOffPhone;
}
}
1] The TU Project folder is located at c:\TU. Inside the project is a folder, called bin, that holds the binary executable.
By default, the binary executable is named like the project with an .exe extension. If you double-click on file TU.exe,
it will launch the form above without having to load Visual Studio.
Purpose
The purpose of this tutorial is to show how to configure, name, and manipulate buttons in a basic Windows
Application with Visual Studio.
If You Have Difficulty With This Tutorial, You Might Find These Help Prepare You For This Tutorial
I Recommend That My Students Complete The Tutorials In This Order!
Tutorial: Visual Studio 2008 Install
Tutorial: Visual Studio 2008 SP1 Install
Tutorial: Visual Studio Windows Application - Forms - Basic Forms
Tutorial: Visual Studio Windows Application - Forms - Labels & TextBoxes
Creating A Button
1] Buttons are used to enable the user to trigger events; To create a Button on the form, drag a Button from the
Toolbox to the Faculty form. We are about to create a button to Exit the application. (See Below!)
1] The Button is an object created on the form with the line of code:
this.button1 = new System.Windows.Forms.Button();
2] When you select the form with the mouse, you can see a box that identifies object Button1. Note the appearance
of the cross-hairs icon
when the mouse is moved over object Button1 below. (See Below!)
3] If you right mouse click on the Button, you can drag it to the desired location on the form. Note the box that is
formed around the Button as you move it.
1] Go to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties)
Below!)
(See
2] Select the Font Property. You can see that the current font is 12pt Ariel bold. Suppose we wish to change the font
to Comic Sans MS. Hold down the font selector
(See Below!)
3] Select the Comic Sans MS font - Regular style - 16 point. Using the mouse, select/push the OK button. (See
Below!)
5] You may select select and change multiple Buttons, using the procedure outlined above, at one time.
6] When doing multiple Buttons, it is often more efficient to set the Font associated with the form; thus it becomes
the default.
1] Return to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties). Select
the ForeColor Property. (See Below!)
and select Maroon from the Custom Color Pallet. (See Below!)
1] Return to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties). Select
the BackColor Property. You can see that the current backcolor is navy. Suppose we wish to change the forecolor to a
compatable blue-gray color. (See Below!)
3] Load http://colorhunter.com into your browser and upload your image (See Below!)
4] I wish to make my buttons like the second color above. Highlight the Navy beside BackColor (See Below!)
1] I ultimately want my text to fit the button. Now that we have demonstrated how to change the button font and
color, take a moment to change your button to your button font to 12 pt bold Ariel Gold as shown below.
2] Return to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties). Select
the Text Property. You can see that the current text is button1. Suppose we wish to change the text to First Name.
Change the Text Property to Exit. (See Below!)
4] This form still executes; try it. Note that the Button object is no longer outlined. (See Below!)
1] Select the button with the mouse. You can drag from the top to make it higher, drag from the bottom to make it
lower, drag from the right to expand in that direction, and drag from the left to expand it in that direction. You can
also drag at a diagonal from any corner. Try it.
(See Below!)
2] In the screen capture below, you can see that I am dragging/expanding the exit button on the left. (See Below!)
Naming A Button
1] You should name every Button. The name should contain no blanks. Suppose we wish to name the Button btnExit; you might also name it cmdExit.
2] Return to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties). Select
the Name Property. You can see that the current name is Button1. Change the Name Property to btnExit. (See
Below!)
2] You can see that the Button below has now been named.
2] When you double click on a button, it automatically creates a shell for the button's click event in the class code
file. You can see the shell for btnExit_Click in the Facutlty.cs file below. The cursor is even placed in the procedure;
we are ready to insert code.
5] Run/Compile/Execute your application. Try the Exit button! When the button is pushed/clicked, the click event
associated with that named button is automatically fired; the application then stops. (See Below!)
1] I downloaded the image below from the Internet. It is neither creative nor good, but it was s bit easier than
drawing one with a paint package. I would like to use it on my Faculty form.
3] Return to the properties panel for the Button (right mouse clicking on the Button. --> Select Properties). Select
the Image Property. You can see that there is no current image. Hold down the font selector
Below!)(See Below!)
(See
4] Import the image into the project. Using the mouse, select/push the Import button below.
6] The Exit Image has now been added to the Resource file associated with the project. Using the mouse select/push
the OK button. (See Below!)
7] The button needs to be reshaped. The exit text needs to be removed. (See Below!)
9] You can use any image from the internet, any image from a button collection or any image you draw as a
background for your buttons. (See Below!)
10] This exit image is not very good, but it might be better if you shaded the background. (See Below!)
2] The left image, below, shows a standard flatstyle button; the right image, below, shows a standard flatstyle button
with mouse over. There is no obvious difference.
4] The left image, below, shows a popup flatstyle button; the right image, below, shows a popup flatstyle button with
mouse over. Note a slight difference around the image border as it turns light blue.
6] The left image, below, shows a flat flatstyle button; the right image, below, shows a flat flatstyle button with
mouse over. Note a definite difference in color. It is much more obvious that this is a button. I often use flat!
1] Add Button btnShowName to your form. You may copy and past the btnExit and rename! (See Below!)
2] Double click on Button btnShowName and add the following code! (See Below!)
3] The call to MessageBox.Show brings up a message box and displays the string passed as an argumet. (See Below!)
4] This is cool, but it does not show the full name. Change the code to the following:
5] Enter a First Name and push the ShowName button. (See Below!)
6] The call to MessageBox.Show brings up a message box and displays the string passed as an argument. (See
Below!)
7] This is cool, but it does not show the full name. Change the code to the following:
9] The call to MessageBox.Show brings up a message box and displays the string passed as an argument. (See
Below!)
10] A more compact version of code which does the same thing can be seen below. (See Below!)
11] This is cool, but it does not show the full name. Change the code to the following:
12] Enter data such as that below and push the ShowName button. (See Below!)
13] Note that all of the character-type data has been changed to upper case. (See Below!)
14] This is cool, but it does not show the full name. Change the code to the following:
15] Enter data such as that below and push the ShowName button. (See Below!)
Purpose
The purpose of this tutorial is to show how to configure, name, and manipulate menus in a basic Windows Application
with Visual Studio; buttons on a single form shall open multiple database forms within a single application.
Tutorial: MSSQL-Forms - Windows Application & Basic Form Properties
Design Considerations
1] It is always best to think about design at the beginning of a project. The best way to design a menu driven system
is to design the upper level main menu first and design your lower-level data forms later. This is great in theory, but I
have found that my students often design at least one or two of the lower-level data forms before they begin to think
about the main menu.
2] Within this tutorial, I am going to assume that we have already completed the TU Faculty form backed up
in directory C:\TU-Faculty. We will try to figure out how to get that form into our new menu driven system.
3] Let us assume that we would like to have an upper level menu with four options:
1.
2.
3.
4.
1] Using the mouse, right mouse click on TU Project --> Select Add --> Select Windows Form ... (See Below!)
2] We are going to design a basic form to be used as a model for all of our application data forms. Let's call this form
TUForm.cs. Using the mouse, select/push the Add button. (See Below!)
Configure This Form To Be A Template That Can Be Used For Other Forms
1] Rather than repeatedly change the default fonts, colors, etc. for all forms throughout the life cycle of this
application, let us create one basic form; we can then copy and paste that basic form over and over.
2] Visual Studio would enable us to design a formal template for the form that would appear in the new item list
above; that is beyond the scope and complexity of this tutorial.
3] Change the name of Form1.cs to MainMenu.cs
4] Select a background Color (Dark Blue) for the application.
5] Select a default Font face (Arie), Font Color (White), Font Style (Bold)
6] Set this from to open on the left below your MainMenu form.
7] Leave the title blank.
1] Using the mouse, right mouse click on TUForms.cs --> Select Copy. (See Below!)
2] Using the mouse, right mouse click on TU Project --> Select Paste. (See Below!)
3] Right mouse click on Copy of TuForms.cs --> Select Rename. (See Below!)
1] An error message, similar to the one below, is generated when two of your forms have the same name.
6] You should now be able to open the faculty form by pushing the button on the main menu. You should be able to
close it and reopen it agian. Adjust the Location Property until the form opens on the left side of you screen slightly
below the main menu. (See Below!)
6] You should now be able to open the faculty form by pushing the button on the main menu. You should be able to
close it and reopen it agian. Adjust the Location Property of the Student Menu until the form opens slightly below and
slightly right of the Faculty Menu. Note that you can open and close both. (See Below!)
6] Note that when you close the main form, both the Student and Faculty forms close as well.
6] You should now be able to open the SpecialtyID form by pushing the button on the main menu. You should be able
to close it and reopen it agian. Adjust the Location Property of the SpecialtyID Menu until the form opens slightly
below and slightly right of the Student Menu. Note that you can open and close all three forms. (See Below!)
6] Note that when you close the main form, both the Student and Faculty and the SpecialtyID forms close as well.
3] Test the application to make sure that all four buttons function properly.
3] Return to the menu-driven TU system. Open the Faculty.cs form. (See Below!)
4] Paste the data and move into place with your mouse.
2] The Exit button on the form does not work. When you do the copy/paste, you get all of the objects, but not the
code behind. If you wanted the code behind, you could enter the .cs file and copy/past it into the .cs file. The code
behind button Exit wasApplication.Exit(). Since we do not want the Faculty form to kll the whole application, let us
simply remove the button from our form.
1] On another tutorial, I will show you how to get data from the form into the MSSQL database. For the moment, let
us suppose that you have started the Faculty Sub-System in order to add a new faculty member. Enter only the first
four fields as shown below.
2] Let us now suppose that you get a phone call and must open up the Student Sub-System. Do it. Let us suppose
that you have looked up the phone number for Jane Doe.
3] Suppose that in the process of working, you close the Faculty form by selecting the X in the top right corner. Do it.
4] Now you are finished with the Student Subsystem. Close the Student Sub-System.
5] You are now ready to finish entering the faculty member Tom Hicks. Once more select the Faculty-Subsystem.
6] We have a problem - the data is gone! Yuk!
7] Suppose Jane never called us back and once more I need to find Jane. If you select the Student-Subsystem, you
will find that you have to look up Jane's record again. Yuk!
8] Perhaps there is a way to change the state of the forms so that when we click the menu button at the top, it
returns us to the previous state of that sub-system.
1] Open the code for MainMenu.cs. The proper way to handle the state problem is to create the forms in the
MainMenu() constructor and show them in the button code. In order for the both the constructor and the button code
to have access to variables faculty, student, and specialthid, they must be declared at the the top of the form as
shown below.
2] Add the three lines of code to initialize/create the three form objects to the constructor. (See Above!)
3] The button click event needs only to show the respective forms. (See Below!)
4] Run MainMenu.cs. When you load the faculty form the first time it works great. When you close it with the X at the
top of the form and then re-load it you get the following error. Yuk!
5] We can eliminate this error by placing a close button to each of our forms. Create btnClose.
6] The one line of code for the btnClose click event is as follows:
7] Copy and paste the btnClose to forms Student and SpecialtyID, add the code behind each of the buttons as well.
8] Run the application. Load all three forms. Move them around to where you can see them. Enter some data the First
Name, Last Name, and ID into the faculty form as shown below.
9] Push the Close buttons on all of the forms. Push the Faculty button on the Menu once more. Note that the state
remains constant - the data is still there!.
10] All is going to work well until the user forgets and closes one of the boxes with the x. This will happen over and
over. Yuk!
11] Solution I is to change the FormBorderStyle Property on the Faculty Form to None. (See Below!)
12] Solution I eliminates the error problem, but the Faculty window can not be moved. It can not be minimized! It
has to icon to identify the app. It has no title to clearly distinguish this Sub-System from another. Yuk! (See Below!)
15] Solution II is certainly better than Solution I. The title bar enables you to distinguish one Sub-System from
another. The window can be moved.. It has an icon to identify the app. Unfortunately it can not be minimized; there
is enough help on the internet to enable you to write a custom minimize button (See Below!)
18] As you can see below, this code simply disables the close box. We can still use the app icon, the title bar, the
minimize, and maximize buttons should we choose.
19] This is such a good solution, that I wanted to provide you with the code in electronic form; you can copy and
paste it into your form files.
private const int CS_NOCLOSE = 0x200;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CS_NOCLOSE;
return cp;
}
}
MenuStrip Objects
1] MenuStrip objects offer an alternative to the button-oriented approach illustrated in this system.
1] This application is a long way from complete. The Student form and SpecialtyID form need to be populated with
data. All three forms will need buttons like New, Delete, Edit, Cancel, Next, Previous, Print, etc.
2] Visual Studio has the ability to design custom, non-rectangular windows. Enjoy!
Purpose
The purpose of this tutorial is to show how to configure, name, and manipulate menu strips in a basic Windows
Application with Visual Studio; buttons on a single menustrip shall open multiple database forms within a single
application.
If You Have Difficulty With This Tutorial, You Might Find These Help Prepare You For This Tutorial
I Recommend That My Students Complete The Tutorials In This Order!
Tutorial: Visual Studio 2008 Install
Tutorial: Visual Studio 2008 SP1 Install
Tutorial: Visual Studio Windows Application - Forms - Basic Forms
Tutorial: Visual Studio Windows Application - Forms - Labels & TextBoxes
Tutorial: Visual Studio Windows Application - Forms - Buttons & Color Picker
Tutorial: Visual Studio Windows Application - Forms - Menu Driven Application With Multiple Forms
1] Launch Visual Studio and create a windows application called GarageManagement. (See Below!)
2] Change the name of Form1 to Application GarageManagementApplication. Using the mouse, right mouse click
on Form1 and select Rename. (See Below!)
3] When ask about renaming all references, select Yes. (See Below!)
4] Using the mouse, right mouse click on the form and select Properties. Change the form Text property to Garage
Management Application. (See Below!
1] The first step in configuring this Application form to house all of our Garage Application forms is to make our form
a Multi Document Interface type form. Change the IsMdIContainer property of the Garage Management Application
form to True. (See Below).
1] Using the mouse, drag the MenuStrip from the toolbox to the top of the Garage Management Appplication form.
(See Below!)
2] Note that the MenuStrip object actually appears below the window. Right mouse click on the MenuStrip and select
Properties. (See Below!)
1] Move the mouse into the far left cell of the MainMenu (See Below!) Enter Login. Change the Name property
to Login as well. (See Below!)
2] Move the mouse into the next cell of the MainMenu (See Below!) Enter Customers. Change the Name property
to Customers as well. (See Below!)
3] Move the mouse down below Customers in MainMenu (See Below!) Enter Add New Customer. Change
the Name property to AddNewCustomer as well. (See Below!)
4] Move the mouse down below Customers in MainMenu (See Below!) Enter Search Customers. Change
the Name property to SearchCustomers as well. (See Below!)
5] Move the mouse To the Right Of Search Customers (See Below!) Enter By Name. Change the Name property
to SearchCustomersByName as well. (See Below!)
CC
6] Move the mouse below SearchByName of the MainMenu (See Below!) Enter By ID. Change the Name Property
to SearchCustomersByID as well. (See Below!)
7] Move the mouse below SearchCustomers of the MainMenu (See Below!) Enter Print Reports. Change
the Name Property to CustomerPrintReports as well. (See Below!)
8] Move the mouse below CustomerPrintReports of the MainMenu (See Below!) Enter View Customer. Change
the Name Property to ViewCustomer as well. (See Below!)
9] Creating menus is often a work in progress. Suppose we look at this application and realize that the View Customer
is the most often used choice within the Customers menu; thus we would like it to be the top choice. You can see in
the series of screen captures below how selected ViewCustomer by pressing on it with the mouse and then I drug the
cell upward one row at a time until it reached the top; I then let go of the mouse. (See Below!)
10] Although you could do it with code, it is a simple process to re-organize the menu choices with the mouse. You
can also copy and paste menu components. (See Below!)
11] Move the mouse into the next cell of the MainMenu (See Below!) Enter Customer Purchases. Change
the Name property to CustomerPurchases as well. Were this a real application, there would be many more menu
choices below CustomerPurchase, but this shall suffice for an educational tutorial. (See Below!)
12] Move the mouse into the next cell of the MainMenu (See Below!) Enter Inventory. Change the Name property
to Inventory as well. Were this a real application, there would be many more menu choices below Inventory, but this
shall suffice for an educational tutorial. (See Below!)
13] Move the mouse into the next cell of the MainMenu (See Below!) Enter Purchase Orders. Change
the Name property to PurchaseOrders as well. Were this a real application, there would be many more menu
choices below PurchaseOrders, but this shall suffice for an educational tutorial. (See Below!)
14] Move the mouse into the next cell of the MainMenu (See Below!) Enter Suppliers. Change the Name property
to Suppliers as well. Were this a real application, there would be many more menu choices below Suppliers, but this
shall suffice for an educational tutorial. (See Below!)
15] Move the mouse into the next cell of the MainMenu (See Below!) Enter Scheduling. Change the Name property
to Scheduling as well. Were this a real application, there would be many more menu choices below Scheduling, but
this shall suffice for an educational tutorial. (See Below!)
15] Move the mouse into the next cell of the MainMenu (See Below!) Enter Exit. Change the Name property
to Exit as well. Were this a real application, I would add Lock and Logout below. (See Below!)
1] Using the mouse, select the MenuStirp. Right mouse click on the MenuStirp and select Properties. Select the
beside the Font property. (See Below!)
2] Select Tahoma 11 point bold font for the MenuStrip. (See Below!)
3] It is beyond the scope of this tutorial, but you can change font face, font size, font style, and font color for
individual menu items as well. See our MenuStrip below. (See Below!)
1] Using the mouse, select the MenuStirp. Right mouse click on the MenuStirp and select Properties. Select the
beside the BackColor property. (See Below!)
2] Select the PaleGoldenrod from the Web pallet. Try changing the font to 12 point Arial. (See Below!)
1] Using the mouse, push on Customers; select the desired color in the ForeColor property at the left. I have chosen
a shade of Blue. (See Below!)
2] Likewise, you can select the ViewCustomer sub-menu under Customers and change the ForeColor property to a
shade of Red. (See Below!)
1] Using the mouse, right mouse click on the View Customer sub-menu item and change the BackColor property to
DarkKahki. (See Below!)
2] Change the other Customers sub-menu BackColor to DarkKahki. You can hold the control key and select all of
them at one time if you like. (See Below!)
1] Using the mouse, hold down the Project Menu and select Add Windows Form... (See Below!)
2] Select the Windows Form template. Name the form ViewCustomers.cs. Using the mouse, select/push the Add
button. (See Below!)
3] A tab frame and a variety of buttons have been added to form Customers.cs. It is a great idea to use Tool Tips to
support almost all of your buttons. (See Below!)
1] Right mouse click on the Garage Management Application form and select View Code. (See Below!)
2] By creating the ViewCustomersForm at the top of the GarageManagement Form, the form object will be available
to all other forms and buttons in the Garage Application. (See Below!)
3] The GarageManagementApplication has already been designated as a Multi Document Interface type form
when IsMdIContainer was set to True. We are now making the ViewCustomers a child form of parent form
GarageManagementApplication. Now that this form has been created and associated with the
GarageManagementApplication, it may be shown quickly at any time. (See Below!)
1] Using the mouse, right mouse click on the Garage Management Application form and select Properties. I am going
to very carefully show you how to use the GUI to assign the events to the MenuStrip. Use the mouse and touch the
Customers menu item one time. (See Below!)
2] Using the mouse, touch the View Customer menu item one time. (See Below!)
button at the top of the Properties bar. Note that the View
4] Using the mouse, double click on the Click event field. (See Below!)
5] A ViewCustomer_Click event was just created. Enter the line of code to show the ViewCustomerForm. (See Below!)
6] Launch the Garage Management Application form.Using the mouse, select View Customer. (See Below!)
7] Once the other forms are complete, you may can be editing an existing customer when you get a call from one of
your suppliers about a Purchase Order you sent. You can minimize the Customer form if you like; it will fall to the
bottom of the Garage Management Application form. You can then look up the Purchase Order. You may have several
windows open at any given time. The Multi Document Interface helps to contain the many forms for the
application. (See Below!)
Login Form
2] Create LoginForm at the top of public partial class GarageManagementApplication : Form. Add the line of code
below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the Login_Click event with the Garage Management Application MenuStrip Item.
Enter the line of code to show the form. (See Below!)
Inventory Form
2] Create InventoryForm at the top of public partial class GarageManagementApplication : Form. Add the line of code
below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the Inventory_Click event with the Garage Management Application MenuStrip
Item. Enter the line of code to show the form. (See Below!)
Suppliers Form
2] Create Supplier Form at the top of public partial class GarageManagementApplication : Form. Add the line of code
below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the Suppliers_Click event with the Garage Management Application MenuStrip
Item. Enter the line of code to show the form. (See Below!)
2] Create PurchaseOrders Form at the top of public partial class GarageManagementApplication : Form. Add the line
of code below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the PurchaseOrders_Click event with the Garage Management Application
MenuStrip Item. Enter the line of code to show the form. (See Below!)
2] Create CustomerPurchases Form at the top of public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the CustomerPurchases_Click event with the Garage Management Application
MenuStrip Item. Enter the line of code to show the form. (See Below!)
Scheduling Form
2] Create Scheduling Form at the top of public partial class GarageManagementApplication : Form. Add the line of
code below. (See Below!)
3] Associate this new form with the Mdi parent in public partial class GarageManagementApplication : Form. Add the
line of code below. (See Below!)
4] Use the Events button to associate the Scheduling_Click event with the Garage Management Application MenuStrip
Item. Enter the line of code to show the form. (See Below!)
1] Shown below are window forms dropped to the bottom of the Garage Management Application. (See Below!)
Purpose
1] This tutorial is going to create a ParentForm which contains two public variables, No and ParentData. It will
create a ChildForm which has access to both No and ParentData; this child form shall change
the ParentData string.
2] There are a number of ways to pass information between parent and child forms, but this seems to be about the
easiest.
1] Add a text box, called txtData. Add a label, whose text is txtData =. (See Below!)
1] Add two public variables, called ParentData and No, to your Parent Form. Initialize ParentData to "Help
Me!" and No to 4. (See Below!)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace PassingDataFromChildToParent
{
public partial class ParentForm : Form
{
public String ParentData = "Help Me!";
public long No = 4;
1] Add a button, called btnUpdateData, to your form; the text for the form is to be Update Data. (See Below!)
2] The purpose of btnUpdateData is to simply transfer a copy of the ParentData string into the txtData textbox.
Using the mouse, double-click on btnUpdateData and add the following code. (See Below!)
3] Run your application. Push the Update Data button. Help Me! should be transferred into the txtData textbox. Your
results should be similar to those below! (See Below!)
1] Add a button, called btnShowNo, to your form; the text for the form is to be Show No. (See Below!)
2] The purpose of btnShowNo is to simply transfer a copy of the ParentData string into the txtData textbox. Using
the mouse, double-click on btnShowNo and add the following code. (See Below!)
4] Parent->No = 4 should be displayed in the MessageBox. Your results should be similar to those below!
1] Add a button, called btnDoubleNo, to your form; the text for the form is to be Double No. (See Below!)
2] The purpose of btnDoubleNo to double the long integer value stored in No. Using the mouse, double-click
on btnDoubleNo and add the following code. (See Below!)
4] Now push the Show No button. Parent->No = 8 should be displayed in the MessageBox. Your results should be
similar to those below!
1] Add a button, called btnDoubleNo, to your form; the text for the form is to be Double No. (See Below!)
2] The purpose of btnDoubleNo to double the long integer value stored in No. Using the mouse, double-click
on btnDoubleNo and add the following code. (See Below!)
4] Now push the Show No button. Parent->No = 8 should be displayed in the MessageBox. Your results should be
similar to those below!
1] Add a text box, called txtData. Add a label, whose text is txtData =. (See Below!)
1] Add a button, called btnOpenChildForm, to your form; the text for the form is to be Open Child Form. (See
Below!)
2] The purpose of btnOpenChildForm is to simply open the child form. Using the mouse, double-click
on btnOpenChildForm and add the following code. (See Below!)
3] Run your application. Push the Open Child Form button. (See Below!)
1] Add a text box, called txtData. Add a label, whose text is txtData =. (See Below!)
1] Add a button, called btnOpenChildForm, to your form; the text for the form is to be Open Child Form. (See
Below!)
2] The purpose of btnOpenChildForm is to simply open the child form. Using the mouse, double-click
on btnOpenChildForm and add the following code. (See Below!)
1] We would like to access No and ParentData from the child form. Since the two variables are public in the
ParentForm, most people try something like the following:
2] Add a button, called btnOpenChildForm, to your form; the text for the form is to be Open Child Form. (See
Below!)
3] The purpose of btnOpenChildForm is to simply open the child form. Using the mouse, double-click
on btnOpenChildForm and add the following code. The program will not compile because we do not have access to
the data. (See Below!)
1] Change The ChildForm: One of the ways to pass data between forms is to send a reference to the parent form to
the child constructor. This is a two step process that begins by creating a ParentForm variable in the ChildForm. Add
pf to your Child Form. (See Below!)
2] Change The ChildForm: Add a second constructor to the ChildForm; passed to this constructor will be a reference
to the ParentForm. Add this second constructor to your code.
4] Change The ParentForm: Call this second variation of the constructor in btnOpenChildForm. (See Below!)
(See Below!)
5] Note that we can now Show No from either form. (See Below!) You might even want to push Double periodically?
6] The ChildForm is now able to access public numeric data in the ParentForm.
1] Add a button, called btnShowParentData, to your form; the text for the form is to be Show ParentData. (See
Below!)
2] The purpose of btnShowParentDatais to simply open the child form. Using the mouse, double-click
on btnOpenChildForm and add the following code. (See Below!)
3] Push button Update Data in the ParentForm and button Show ParentData in the ChildForm. (See Below!)
4] The ChildForm is now able to access public string data in the ParentForm.
1] Add a button, called btnTransferData, to your form; the text for the form is to be Transfer Data To
Parent. Thus far, we have not used the textbox in the Child. (See Below!)
2] The purpose of btnTransferData to copy the contents of the txtData textbox into the string variable ParentData.
Using the mouse, double-click on btnTransferData and add the following code. (See Below!)
3] ParentData contains Help Me!. Trinity University Computer Science is entered into ClientForm->txtData. The
Transfer Data Above To Parent button is pushed. (See Below!)
5] The ChildForm has just changed the ParentForm. Passing the ParentForm reference to the ChildForm enables the
ChildForm to change any public items in the ParentForm; in addition to variables, one can change labels, textboxes,
combo boxes, etc. (See Below!)
Project PassingDataBetweenForms
1] In order for the ChildForm to change the ParentForm->txtData, it must be public. Open the
ParentForm.Designer.cs and make it so. (See Below!)
1] Go to the ChildForm. Double-click on the txtData textbox. Add the code below for the event. With each and every
change to the ChildForm-txtData, the ParentForm->txtData will automatically be updated. (See Below!)
2] Run the application. Open the Child Form. Enter Trinity University in the txtData field of the ChildForm. (See
Below!)
Purpose
The purpose of this tutorial is to show how to add a web browser control to a Windows Application Form, using Visual
Studio.
Applicability
1] Although you could easily create your own custom browser, it is much more likely to be the case that you would
like to access web based media on a windows application.
2] Combining a database with the webbrowser is a great way to dynamically generate content from a database;
although this is beyond the scope of this tutorial, the construction of the browser object below will be helpful.
1] I would like the top right corner of my form to be a WebBrowser. Using the mouse, drag the WebBrowser from the
toolbox to your form and size it accordingly. (See Below!)
2] The default name for the WebBrowser object is webbrowser1; this is fine for our application.
3] Change the URL property of the webbrowser object to the URL to be loaded when the form is launched, if any. I
am entering http://cs.trinity.edu. (See Below!)
3] Rename the form to WebBrowserDemo. Use the form Text property to add an appropriate commercial to the form.
Select a color, font, and font color for your application. Execute your form. Try the links on the pages and you will see
that they work well. (See Below!)
Enable The User To Select The URL With A Textbox And A Button.
2] Drag a button to your form. Change the Text property of the button to be Go. Change the button name
to btnGoURL. (See Below!)
3] Double click on the Go button. Add the following code to btnGo_Click event.
4] Enter either google.com or http://google.com in the text box. Push the Go button. (See Below!)
5] If you leave the form blank, it will display the message box. If you enter an invalid URL, it does nothing. If you
enter a valid URL, it navigates to the page. (See Google Below!)
1] Drag a button to your form. Change the Text property of the button to be Back. Change the button name
to btnBack. (See Below!)
2] Double click on the Back button. Add the following code to btnBack_Click event. (See Below!)
3] Load your page. Select a link on the page, such as the About link on the Trinity Computer Science page. Push the
back button; it returns you to your original page.
1] Drag a button to your form. Change the Text property of the button to be Forward. Change the button name
to btnForward. (See Below!)
2] Double click on the Forward button. Add the following code to btnForward_Click event. (See Below!)
3] Load your page. Select a link on the page, such as the About link on the Trinity Computer Science page. Push the
back button; push the back button. Note that it takes remarkably little code to implement browser functionality.
1] Microsoft makes distributes a free version of Microsoft SQL Server 2008. It is so functional and reliable that a
number of companies never need to upgrade to a pay version. The advanced package includes a number of additional
support tools - such as Microsoft SQL Server Management Studio Express. Microsoft SQL Management Studio Express
is a GUI tool which enables you to create databases, records, queries, etc. I encourage you to download and install
the advanced version of the software.
Pre-Requisite Software
1] If you are going to install Visual Studio 2008, I recommend that you do it first.
Tutorial: VisualStudio-2008-Install
2] I recommend that you install all service packs for your operating system before you begin. My students often skip
the requirements and waste installation time because Microsoft SQL Server 2008 Advanced will simply not install
unless you have the following software on your computer:
.NET 3.5 with Service Pack 1 Tutorial : .NET-3.5-Install
Windows Installer 4.5 Tutorial : Windows-Installer-4.5-Install
Windows Power Shell Tutorial : Windows-Power-Shell-2.0-Install
Visual Studio 2008 Service Pack 1 (if you have Visual Studio 2008) Tutorial : Visual-Studio-2008-SP1-Install
1] Either go to Microsoft.com and download the newest version of the software or use the one below:
SQL-Server-2008-Adv.zip
2] Using the mouse, select the Installation tab on the left. Select New SQL Server Stand-Alone Installation on the
right. (See Below!)
3] Hopefully you will have nothing to correct in the failure listing below. Once you get the opportunity, push/select
the OK button at the bottom. (See Below!)
4] Using the mouse, select/push the Next button at the bottom. (See Below!)
5] Read and accept the license agreement. Using the mouse, select/push the Next button at the bottom. (See
Below!)
6] Using the mouse, select/push the Install button at the bottom. (See Below!)
7] Note that my system passed all of the required support rules. The ability to access this server, from a remote
system, can be blocked by any software firewall. I normally keep my firewall off when behind a router and enable it if
I am using the computer in a public venue. You might also have warnings from anti-virus systems that help to protect
your ports. I am going to click on the Windows Firewall warning below.
8] It is beyond the scope of this tutorial to open the Windows Firewall ports to enable remote server access across a
network. You can get directions to do so by following the Microsoft link below. Write down the link. Using the mouse,
push/select the OKbutton. (See Below!)
9] Using the mouse, select/push the Next button at the bottom. (See Below!)
10] Using the mouse, select/push the Next button at the bottom. (See Below!)
11] Read through and Accept the License Agreement. Using the mouse, push/select the Next button. (See Below!)
12] Using the mouse, push/select the Select All button. Using the mouse, push/select the Select All button.
13] As you look at the Instance Configuration below, you can note that this computer already has an instance
called SQLExpress; we must name this new instance something different. I am choosing SQL.
I would like my students to name this instance SQL.
Using the mouse, push/select the Next button at the bottom. (See Below!)
14] Using the mouse, push/select the Next button at the bottom. (See Below!)
15] We must now provide access authentication. You must use some administrative account to install the service.
Replace the thicks & corresponding password with an administrative account on your server. Using the mouse,
select/push the Next button. (See Below)
16] I would like my students to install this with Windows authentication. You can always enable the
Mixed Mode later. I would like my students to add thicks, administrator, and the names of all of the
server adminstrators to the unrestricted access list below. Push/select the Next button. (See Below!)
I would like my students to add thicks, administrator, and each person in their server group.
17] Using the mouse, select/push the Next button. (See Below)
18] Using the mouse, select/push the Next button. (See Below)
19] Using the mouse, select/push the Next button. (See Below)
20] Using the mouse, select/push the Next button. (See Below)
22] Using the mouse, select/push the Next button. (See Below)
23] Using the mouse, select/push the Close button. (See Below)
1] Open the Control Panel. Using the mouse, double-click on Administrative Tools. (See Below!0
3] If you followed the installation directions above and rebooted your computer, you should see instance SQL of SQL
Server started automatically. Note that this system has instance SQLEXPRESS running as well; it was installed with
Visual Studio. It is ok to have both running.. (See Below!)
1] Using the mouse, hold down the Start Menu --> Select Microsoft SQL Server 2008 --> Select SQL Server
Management Studio
2] Although I could simply enter the server name, I am going to use the server name drop-down to search for it;
using the mouse, hold down the drop-down --> Select Browse for more ...
3] Expand Database Engine. Select the SQL instance. The name of my computer is Laptop; this name precedes both
server instances. (See Below)
4] I could have simply typed in LAPTOP\SQL for the server name. Using the mouse, push/select
the Connect button. (See Below)
5] Microsoft SQL Server Management Studio provides a free GUI that enables you to create databases, tables,
queries, etc., but using this application is a topic for another day. (See Below)
Purpose
The purpose of this tutorial is to show how to use Microsoft SQL Server Management Studio Express to (1) create
Microsoft SQL Server Express database, (2) create database tables, (3) add data to tables, and show the data in
tables.
If You Have Difficulty With This Tutorial, You Might Find These Help Prepare You For This Tutorial
I Recommend That My Students Complete The Tutorials In This Order!
Tutorial: Microsft SQL Server Express- 2008 Advanced (With Server Management Studio) Express Install
1] Open Microsoft SQL Management Studio, or Microsoft SQL Management Studio Express. Using the mouse, right
mouse click on Databases --> Select New Database ... (See Below!)
2] Name the database TU. Using the mouse, select/push the OK button. (See Below!)
1] Expand the TU database. Right mouse click on Tables and select New Table ... (See Below!)
2] Add fields FirstName, LastName, ID, Gender, SpecialtyID, and About to your new database table; you can
see the data types in the screen capture below. The SpecialtyID field in an integer; in order to get the MSSQL
database to auto number, set theIdentity Specification to Yes. Using the mouse, select/push the OK button. (See
Below!)
3] Now that the database table is defined, it is time to save the Table. Using the mouse, hold down the File Menu -->
Select Save Table_1 (See Below!)
4] Name the table Faculty. Using the mouse, select/push the OK button. (See Below!)
5] You can see that the Faculty Table has now been added to the TU database. (See Below!)
1] Right mouse click on Tables and select New Table ... (See Below!)
2] Add fields SpecialtyID, and Description to your new database table; you can see the data types in the screen
capture below. The SpecialtyID field in an integer; in order to get the MSSQL database to auto number, set
the Identity Specification to Yes. Using the mouse, select/push the OK button. (See Below!)
3] Now that the database table is defined, it is time to save the Table. Using the mouse, hold down the File Menu -->
Select Save Table_1 (See Below!)
4] Name the table Specialty. Using the mouse, select/push the OK button. (See Below!)
10] You can see that the Specialty Table has now been added to the TU database. (See Below!)
1] Right mouse click on the Specialty Table --> Select Open Table (See Below!)
2] Add records Networking, Database, Simulation, Parallel Processing, Artificial Intelligence, Graphics, and Theory
(As Illustrated Below!)
1] Right mouse click on the Faculty Table --> Select Open Table (See Below!)
2] Add the records for Eggen, Hicks, Massingil, Myers, and Lewis to the table. (As Illustrated Below!)
Tutorial: Import-Export-Backup Of MSSQL Database With Microsoft SQL Server Manager Express
Purpose
The purpose of this tutorial is to show how to use Microsoft SQL Server Management Studio Express to (1) import and
export data to the same instance of the Microsoft SQL Server Express server. The last section of this tutorial shows
how to attach original database data to alternate servers.
If You Have Difficulty With This Tutorial, You Might Find These Help Prepare You For This Tutorial
I Recommend That My Students Complete The Tutorials In This Order!
Tutorial: Microsft SQL Server Express- 2008 Advanced (With Server Management Studio) Express Install
Tutorial: MSSQL Database Construction With Server Management Studio
Why Do
There are a number of reasons that you should back up your databases; three of the more important reasons would
be:
1. All hard drives will eventually go bad; a current backup will enable you to restore the databases.
2. When developers are designing new procedures and queries, they will often test those functions on a backup
copy of the database; once the testing proves to be correct, they can be used on the original database. If the
procedures or queries are found to be faulty, the original database has not been destroyed.
3. There will be times when you wish to transfer a copy of the database to a second computer system. Exporting
from the original database system and Importing to the second computer system will enable you to establish
the second database.
There are a number of reasons that you should back up your databases; three of the more important reasons would
be:
The Database
1] We shall backup the Northwind database on Net1. Note that the Northwind database contains 8 tables.
2] The Customers database table contains 91 records. We shall open up our copy and make sure that the Customers
table looks similar to that below.
Northwind.zip
1] Using the mouse, right-mouse-click on the Northwind Database --> Select Tasks --> Select Back Up... (See
Below!)
2] We are going to do a Full Backup. You can rename the backup, but we are going to leave ours as Northwind-Full
Database Backup. This is going to create a file, called Northwind.bak in directory. Using the mouse, select/push
the OK button. (See Below!)
3] The BackUp takes only seconds to complete. Using the mouse, select/push the OK button. (See Below!)
4] Take a look in directory C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup - you will see
file Northwind.bak. (See Below!)
1] Using the mouse, right-mouse-click on the Northwind Database --> Select Delete (See Below!)
IMPORTING PROBLEMS?
I have found that students are sometimes successful importing from drive C and sometimes not. It
depends upon the permissions associated with the drive C of the computer. They will always have
problems importing from the desktop. In order to consider the permissions we might need, it is best to
examine the default folder that MSSQL uses to backup files. The required permission for the import
is SQLServer2005MSSQLUser
Below, I have shown the default permissions on folder C:\Program Files\Microsoft SQL
Server\MSSQL.1\MSSQL\Backup
3] Name the database Northwind. Select the From Device radio button. Select the
(See Below!)
4] We need to Add the backup file. Using the mouse, select/push the Add button. (See Below!)
5] Locate the backup file in the top window. Using the mouse, select/push the OK button. I have
selected Northwind.bak on C:\ (See Below!)
7] Check the box beside Northwind-Full Database Backup. Using the mouse, select/push the OK button. (See Below!)
9] As you can see below, once again we have a Northwind database whose Customer table has 91 records. This
process can be used to make a copies of the Northwind database on other SQL/SQLEXPRESS Servers. (See Below!)
2] Using the mouse, right-mouse-click on Databases --> Select Restore Database (See Below!)
3] Name the database Northwind2. Select the From Device radio button. Select the
file. (See Below!)
4] We need to Add the backup file. Using the mouse, select/push the Add button. (See Below!)
5] Locate the backup file in the top window. Using the mouse, select/push the OK button. I have
selected Northwind.bak on C:\ (See Below!)
7] Check the box beside Northwind-Full Database Backup. Using the mouse, select/push the OK button. (See Below!)
9] As you can see below, once again we have a Northwind2 database whose Customer table has 91 records. This
process can be used to make a duplicate copy of the Northwind database on the same SQL/SQLEXPRESS Server. This
copy might be used to test procedures and queries; it can also be used for development. (See Below!)
1] Note that I have deleted the OrderDetail and the Orders tables from the Northwind database. I have also reduced
the 91 Customer table records to only 12. (See Below!)
2] Using the mouse, right-mouse-click on Databases --> Select Restore Database (See Below!)
3] Name the database Northwind. Select the From Device radio button. Select the
(See Below!)
4] We need to Add the backup file. Using the mouse, select/push the Add button. (See Below!)
5] Locate the backup file in the top window. Using the mouse, select/push the OK button. I have
selected Northwind.bak on C:\ (See Below!)
7] Check the box beside Northwind-Full Database Backup. Using the mouse, select/push the OK button. (See Below!)
9] As you can see below, once again we have a Northwind database whose Customer table has 91 records. Tables
Order Details and Orders have also been restored. This process can be used to databases on other SQL/SQLEXPRESS
Servers. (See Below!)
1] The techniques above work to backup and restore data from the same database instance. By using attach, we can
get the data into other database instances.
2] You might want to download the two files below and copy them into your SQL Server data directory (see below!)
LibraryApp-Attach
3] Open MSSQL Server Management Studio Express. Right mouse click on Databases and select Attach. (see below!)
5] Select the LibraryApp.mdf in your SQL Server data directory. (see below!)
6] Open MSSQL Server Management Studio Express. Right mouse click on Databases and select Attach. (see below!)
Purpose
The purpose of this tutorial is to show how to configure, name, and manipulate ComboBoxes in a basic Windows
Application with Visual Studio.
1] This tutorial shall examine one control at a time. Each control shall be added to the empty form below. (See
Below!)
1] Using the mouse, drag the ComboBox control from the ToolBox to the form. (See Below!)
1] Suppose I wish to create a combo box to enable the user to select the order in which to cycle through faculty data
records. We might choose to order the faculty members by Name, by ID, or by Department.
2] Every control should be well named. Right mouse click on the ComboBox control and select Properties. Change
the Name property to CBoxOrderBy. (See Below!)
3] One of the ways to to manually fill the ComboBox control is to push the
ComboBox tasks control. (See Below!)
(See Below!)
5] This brings up an String Collection Editor in which we can enter the ComboBox choices. (See Below!)
C
6] A second, and more efficient way to bring up the String Collection Editor would be to push the Collection
button located by the Items Property. (See Below!)
7] Irrespective of how you have brought up the editor, enter Name, by ID, and Department. Using the mouse,
select/push the OK button. (See Below!)
8] Run the form and check out the ComboBox control. Note that it starts out blank.
10] Suppose you wish to initialize the control so that it starts with the ID field selected. By entering "ID" in
the Text property of the ComboBox, it will launch the form with ID appearing in the ComboBox.
1] Most often you will be concerned about the choice selected in ComboBox, called CBoxOrderBy. You might find a
few of the other properties interesting.
2] The result will be found in property CBoxOrderBy.Text. The ComboBox control enables the programmer to logically
get at much of the information in the control. Enter the following chage event in the program; this change event will
be launched each and every time CBoxOrderBy is changed.
private void CBoxOrderBy_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show ("CBoxOrderBy.Selected Text = " + CBoxOrderBy.Text);
MessageBox.Show ("CBoxOrderBy.SelectedIndex = " + CBoxOrderBy.SelectedIndex.ToString());
MessageBox.Show ("CBoxOrderBy.Items[0] = " + CBoxOrderBy.Items[0].ToString());
MessageBox.Show ("CBoxOrderBy.Items[1] = " + CBoxOrderBy.Items[1].ToString());
MessageBox.Show ("CBoxOrderBy.Items[2] = " + CBoxOrderBy.Items[2].ToString());
MessageBox.Show ("CBoxOrderBy.SelectionLength = " + CBoxOrderBy.SelectionLength.ToString());
MessageBox.Show ("CBoxOrderByItems.Count = " + CBoxOrderBy.Items.Count.ToString());
}
4] Once you understand the various properties of the ComboBox, you may fill it, alter it, and manipulate it manually
or programatically. The application above may be downloaded below.
ComboBox-1.zip
1] There are many database programs that can be used to fill ComboBoxes; we shall use Microsoft SQL Server
Express. The TU database has a faculty table and a Specialty table. The Faculty form might very well include a
Specialty ComboBox in which the user can select from the various computer science specialties. You can see the
contents of the Specialty table below.
3] Below is a copy of the TU database; install it on your Microsoft SQL Server Express if you like.
TU.zip
Tutorial: MSSQL Database Import, Export, & Backup With Server-Management-Studio
1] A database connection will be needed to fill the ComboBox. If you look at the Server Explorer below, you can see
that there is already a data connection to our TU database; we could use it.
2] Let us change a couple of names to make them more applicable to the task at hand. Change the text for your label
to Specialty. Delete the CBoxOrderBy ComboBox and create a new ComboBox that is named CBoxSpecialty.
3] For the sake of completeness, I have deleted the connection. We shall make a new one. (See Below!)
Using A Single Database Table Field To Add Choices To The ComboBox Control
1] Push the
(See Below!)
(See Below!)
(See Below!)
4] We have no data sources available. Select the Add Project Data Source link at the bottom. (See Below!)
5] Select Database as the data source type. Using the mouse, select/push the Next button. (See Below!)
6] If we had connections, they would appear in the drop down. We are going to create a new connection. Using the
mouse, select/push the New Connection button. (See Below!)
7] Enter your Server Name. You may be able to select it from the drop down list. Select your authentication type; I
am going to use Windows Authentication. Select your database; I am selecting TU. (See Below!)
11] The TU data connection is now complete. Using the mouse, select/push the Next button.
12] TUConnectionString is fine for a title. Using the mouse, select/push the Next button.
13] It is time to create the DataSet. Open the Specialty database table and select Description. Let us call our new
DataSet TUDescriptionDataSet. Using the mouse, select/push the Finish button.
14] The DataSet is now complete; it is time to bind data to our ComboBox. It is time to designate the Display Member
of the ComboBox. Pull down the Display Member drop down.
(See Below!)
15] Selection the Description link as the Display Member. (See Below!)
16] Before we run the application, you need to note that the tuDescriptionDataSet, the specialtyTableAdapter,
and the specialtyBindingSouce have all been created and added to our form. (See Below!)
1] Most often you will be concerned about the choice selected in ComboBox, called CBoxSpecialty.Text.. You might
find a few of the other properties interesting.
2] The result will be found in property CBoxSpecialty.Text. The ComboBox control enables the programmer to
logically get at much of the information in the control. Enter the following chage event in the program; this change
event will be launched each and every time CBoxSpecialty is changed.
private void CBoxOrderBy_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("DataSet........................: DataSetName = "
+ tUDescriptionDataSet.DataSetName.ToString());
MessageBox.Show("DataSet Table..................: tUDescriptionDataSet.Tables[0] = "
+ tUDescriptionDataSet.Tables[0].ToString());
MessageBox.Show("TableAdap Table................: specialtyTableAdapter.GetData().TableName = "
+ specialtyTableAdapter.GetData().TableName.ToString());
MessageBox.Show("DataSet - First Field..........:
tUDescriptionDataSet.Tables[0].Columns[0].ColumnName = "
+ tUDescriptionDataSet.Tables[0].Columns[0].ColumnName.ToString());
MessageBox.Show("DataSet - First Field..........: tUDescriptionDataSet.Tables[0].Columns[0] = "
+ tUDescriptionDataSet.Tables[0].Columns[0].ToString());
MessageBox.Show("TableAdap First Field..........: specialtyTableAdapter.GetData().Columns[0] = "
+ specialtyTableAdapter.GetData().Columns[0].ToString());
MessageBox.Show("Chosen Item #..........: specialtyBindingSource.Position = "
+ specialtyBindingSource.Position.ToString());
MessageBox.Show("Chosen Item #..................: SelectedIndex = "
+ CBoxSpecialty.SelectedIndex.ToString());
MessageBox.Show("Chosen Description.............: Selected Text = "
+ CBoxSpecialty.Text);
MessageBox.Show("TableAdap DataType-SpecialtyID.:
specialtyTableAdapter.GetData().Columns[0].DataType = "
+ specialtyTableAdapter.GetData().Columns[0].DataType.ToString());
MessageBox.Show("cbox - # Records...............: Items.Count = "
+ CBoxSpecialty.Items.Count.ToString());
MessageBox.Show("TableAdap Table # Records......: specialtyTableAdapter.GetData().Rows.Count = "
+
specialtyTableAdapter.GetData().Rows.Count.ToString());MessageBox.Show("DataSet........................:
DataSetName = "
+ tUDescriptionDataSet.DataSetName.ToString());
MessageBox.Show("DataSet Table..................: tUDescriptionDataSet.Tables[0] = "
+ tUDescriptionDataSet.Tables[0].ToString());
MessageBox.Show("TableAdap Table................: specialtyTableAdapter.GetData().TableName = "
+ specialtyTableAdapter.GetData().TableName.ToString());
MessageBox.Show("DataSet - First Field..........:
tUDescriptionDataSet.Tables[0].Columns[0].ColumnName = "
+ tUDescriptionDataSet.Tables[0].Columns[0].ColumnName.ToString());
MessageBox.Show("DataSet - First Field..........: tUDescriptionDataSet.Tables[0].Columns[0] = "
+ tUDescriptionDataSet.Tables[0].Columns[0].ToString());
MessageBox.Show("TableAdap First Field..........: specialtyTableAdapter.GetData().Columns[0] = "
+ specialtyTableAdapter.GetData().Columns[0].ToString());
MessageBox.Show("Chosen Item #..........: specialtyBindingSource.Position = "
+ specialtyBindingSource.Position.ToString());
MessageBox.Show("Chosen Item #..................: SelectedIndex = "
+ CBoxSpecialty.SelectedIndex.ToString());
MessageBox.Show("Chosen Description.............: Selected Text = "
+ CBoxSpecialty.Text);
MessageBox.Show("TableAdap DataType-SpecialtyID.:
specialtyTableAdapter.GetData().Columns[0].DataType = "
+ specialtyTableAdapter.GetData().Columns[0].DataType.ToString());
MessageBox.Show("cbox - # Records...............: Items.Count = "
+ CBoxSpecialty.Items.Count.ToString());
MessageBox.Show("TableAdap Table # Records......: specialtyTableAdapter.GetData().Rows.Count = "
+ specialtyTableAdapter.GetData().Rows.Count.ToString());
}
MessageBox.Show("TableAdap DataType-SpecialtyID.:
specialtyTableAdapter.GetData().Columns[0].DataType = "
+ specialtyTableAdapter.GetData().Columns[0].DataType.ToString());
specialtyTableAdapter.GetData().Rows.Count = "
+ specialtyTableAdapter.GetData().Rows.Count.ToString());
Project ComboBox-1
1] I am sure that you are most interested in the fact that, CBoxSpecialty.Text above, served as a vehicle by which
we could determine that the user selected the Database specialty.
2] In today's world of reasonable programming, one does not store "Database" in the faculty record. Good design,
irrespective of the language or application, would mandate a Faculty entity/class that contains a numeric variable,
that database would call aforeign key, such as SpecialtyID. (See Below!)
3] Good design, irrespective of the language or application, would mandate a Specialty entity/class that contains a
numeric variable, that database would call a primary key, such as SpecialtyID. . (See Below!)
4] Good design, irrespective of the language or application, would generate a relationship between the
Specialty.SpecialtyID and the Faculty.SpecialtyID. (See Below!)
5]
6] Now we could write a huge case statement or many if-then-else statements on the back end to translate the
ComboBox selection text selection into a numeric value to store in the Faculty record. When there are thousands of
Specialties, this block of code is huge; the problem becomes worse when new specialties are added because the basic
programming code behind the ComboBox control would have to changed.
Suppose the ComboBox control had the ability to store two fields - maybe Description and SpecialtyID. Suppose we
could display, to the user, only the Description and have the ComboBox return the SpecialtyID associated with the
user choice! We can!
1] Duplicate your Specialty label. Add a new ComboBox - Name it CBoxSpecialty2. (See Below!)
1] Push the
selection tool at the top of the new ComboBox. Check the Use Data Bound Items. (See Below!)
(See Below!)
3] Select the Add Project Data Source link at the bottom. (See Below!)
4] Select Database as the data source type. Using the mouse, select/push the Next button. (See Below!)
5] The Database connection that we created earlier can be used for this and any other control using the TU database.
Using the mouse, select/push the Next button. (See Below!)
6] Select both the SpecialtyID and the Description fields of the Specialty table. I shall name the
DataSet TUDescriptionSpecialtyIDDataSet. Using the mouse, select/push the Finish button. (See Below!)
7] The DataSet is now complete; it is time to bind data to our ComboBox. It is time to designate the Display Member
of the ComboBox. Pull down the Display Member drop down.
(See Below!)
9] It is time to designate the Value Member of the ComboBox. Pull down the Display Member drop down.
Below!)
(See
10] Selection the SpecialtyID link as the Value Member. (See Below!)
11] Both the Display Member and the Value Member are now bound to the ComboBox control. (See Below!)
1] Most often you will be concerned about the two choices selected in ComboBox, called CBoxSpecialty2.Text and
CBoxSpecialty2.SelectedValue. You might find a few of the other properties interesting.
2] This control enables the user to select a choice from CBoxSpecialty2Text and to programmatically fill the database
with CBoxSpecialty2.SelectedValue.
private void CBoxSpecialty2_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Extracting Information Out Of The DataSet 2");
MessageBox.Show("DataSet........................: DataSetName = "
+ tUDescriptionSpecialtyIDDataSet.DataSetName.ToString());
MessageBox.Show("DataSet Table..................: tUDescriptionSpecialtyIDDataSet.Tables[0] =
+ tUDescriptionSpecialtyIDDataSet.Tables[0].ToString());
MessageBox.Show("TableAdap Table................: specialtyTableAdapter.GetData().TableName =
+ specialtyTableAdapter.GetData().TableName.ToString());
MessageBox.Show("DataSet - First Field..........:
tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[0].ColumnName = "
+ tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[0].ColumnName.ToString());
MessageBox.Show("DataSet - First Field..........:
tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[0] = "
+ tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[0].ToString());
MessageBox.Show("TableAdap First Field..........: specialtyTableAdapter1.GetData().Columns[0]
+ specialtyTableAdapter.GetData().Columns[0].ToString());
MessageBox.Show("DataSet - Second Field.........:
tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[1].ColumnName = "
+ tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[1].ColumnName.ToString());
MessageBox.Show("DataSet- Second Field..........:
tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[1] = "
+ tUDescriptionSpecialtyIDDataSet.Tables[0].Columns[1].ToString());
MessageBox.Show("TableAdap Second Field.........: specialtyTableAdapter1.GetData().Columns[1]
+ specialtyTableAdapter1.GetData().Columns[1].ToString());
MessageBox.Show("Chosen Item #..........: specialtyBindingSource.Position = "
+ specialtyBindingSource.Position.ToString());
MessageBox.Show("Chosen Item #..................: SelectedIndex = "
+ CBoxSpecialty2.SelectedIndex.ToString());
MessageBox.Show("Chosen Description.............: Selected Text = "
+ CBoxSpecialty2.Text);
MessageBox.Show("CBoxSpecialty2.SelectedValue....: Selected Text = "
+ CBoxSpecialty2.SelectedValue.ToString());
"
"
= "
= "
MessageBox.Show("TableAdap DataType-SpecialtyID.:
specialtyTableAdapter1.GetData().Columns[0].DataType = "
+ specialtyTableAdapter1.GetData().Columns[0].DataType.ToString());
MessageBox.Show("TableAdap DataType-Description.:
specialtyTableAdapter1.GetData().Columns[1].DataType = "
+ specialtyTableAdapter1.GetData().Columns[1].DataType.ToString());
MessageBox.Show("cbox - # Records...............: Items.Count = "
+ CBoxSpecialty2.Items.Count.ToString());
MessageBox.Show("TableAdap Table # Records......: specialtyTableAdapter.GetData().Rows.Count = "
+ specialtyTableAdapter.GetData().Rows.Count.ToString());
}
the results are much the same as we observed in CBoxSpecialty2 above. The following shall reflect only the those
properties not previously illustrated above.
private void CBoxSpecialty2_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("DataSet........................: DataSetName = "
+ tUDescriptionSpecialtyIDDataSet.DataSetName.ToString());
MessageBox.Show("TableAdap DataType-SpecialtyID.:
specialtyTableAdapter1.GetData().Columns[0].DataType = "
+ specialtyTableAdapter1.GetData().Columns[0].DataType.ToString());
MessageBox.Show("TableAdap DataType-Description.:
specialtyTableAdapter1.GetData().Columns[1].DataType = "
+ specialtyTableAdapter1.GetData().Columns[1].DataType.ToString());
the SelectedValue is 2.
1] Using the mouse, right mouse click on CBoxSpecialty and select Properties. Push the
the Font property. (See Below!)
3] Note that the top Specialty Font has been changed. (See Below!)
1] Once again return to the Properties of CBoxSpecialty. Using the mouse push/select the drop down
ForeColor property. (See Below!)
2] Suppose we select the red color from the Custom color pallet. (See Below!)
beside the
1] Once again return to the Properties of CBoxSpecialty. Using the mouse push/select the drop down
BackColor property. (See Below!)
2] Suppose we select the light pink color from the Custom color pallet. (See Below!)
beside the
Tutorial: Tutorial: Tutorial: Visual Studio Windows Application MSSQL Connections (Without GUI) To A
Library Application
Purpose
The purpose of this tutorial is to show how to configure a Windows Application Form, using Visual Studio without
using delegates, to process next, previous, delete, top, bottom, order by, and alphabetical search button controls.
The Database
1] You might want to download and add the following database on the server; call the database LibraryApp. You
can use import from the Microsoft Access database
LibraryApp-Access
Tutorial: MSSQL-Server-From-2003-Access-DB\MSSQL-Server-From-2003-Access-DB
Tutorial: MS-SQL-Server-From-2007-Access-DB\MS-SQL-Server-From-2007-Access-DB
or you might want to try to import the LibraryApp database directly into Microsoft SQL Server using Microsoft SQL
Server Management Studio Express.
LibraryApp
Tutrial: MSSQL Import-Export-Backup-MSSQL-Database
1] Our database is shown, below, via Microsoft SQL Server Management Studio Express. Note that our server, to
which we shall connect, is NET1\SQLEXPRESS (See Below!)
2] There are a number of good ways to connect. We are going to use two connection string options. See the link
below for an Internet link that most of us should keep bookmarked.
http://connectionstrings.com
3] Since we shall connect with both Windows and SQL server authentication, it is important that you configure your
SQL Server to authenticate both ways. An easy way to do this is to use Microsoft SQL Server Management Studio
Express (Right mouse click on Net1\Express and select properties-select Security page). (See Below!)
4] Use Microsoft SQL Server Management Studio Express to create a user, called student whose password
is student. (See Below!)
5] Double-click on the student account; select User Mappings. Use Microsoft SQL Server Management Studio Express
to enable the student user to use the LibraryApp database. (See Below!)
6] Continue to use Microsoft SQL Server Management Studio Express. Right-mouse click on the LibraryApp database
and select Properties. Select the Permissions Page. Add the student user if necessary. The student user certainly does
not need all of the permissions, but for the sake of simplicity (and because I don't want this to be a tutorial on SQL
Server), grant the student user all permissions. (See Below!)
7] SQL user student should now be able to use password student to authenticate with the LibraryApp database
throughout this tutorial.
1] My students have been asked to complete some basic forms to support this tutorial. Firs is LibraryApp.cs, which
uses a MenuStrip to control the main application. The lab description may be seen below. LibraryApp.cs, is to look
something like the following:
MSSQL-Library-App\MSSQL-Library-App-1 Lab
2] They were to create a basic Administrative login form called Login.cs. It is to look something like the following:
3] They were to also create a non-functional ViewUser vorm called Users.cs that looks something like the following:
[We realize that the MajorID and Administrator should eventually be combo boxes and that the password might
eventually be replaced by #'s.
To get rid of the close box, add the following function right below the function public Users()
private const int CS_NOCLOSE = 0x200;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CS_NOCLOSE;
return cp;
}
}
4] They were supposed to place all of the fields, from the Users table, in the first tab frame of the Users form.
5] Button Close should hide the Users Form. Their Users form was to include all of the buttons seen on the form
above and all of the combo boxes seen on that form.
6] A collection of images was made available to the students. They included: Top
and Previous
, Bottom
, Next
.
BitMaps.zip
Top
Bottom
Next
Previous
7] Below you can see, in turquoise, the names I have associated with the various TextBoxes, lLabels, and
ComboBoxes on my Users.cs form.
1] The purpose of this tutorial is to connect to our database, without guis, and add functionality to many of the
buttons on the Users.cs form.
1] You must include the System.Data.SqlClient Namespace at the top of the Users.cs form.
1] If you are working on your SQL Server, using Windows Authentication will probably be the easiest.
2] Using the mouse, double-click someplace on your users form that has no objects; this will create a User_Load
function that will be fired each time our form is loaded. We are going to place our temporary testing code in that
function.
3] In accordance with ConnectionStrings.com, let us define our Connection String to load the Library database on
Net1\SQLExpress. Note the need to use the \\ escape sequence in the connection string. Create a string object,
called ConnectionString, and fill it in accordance with your SQL Server Name. Add the line below to your form and
test it; your form should load, but there will be no evidence that the database stuff is working yet. (See Below!)
String ConnectionString = "Data Source=net1\\SQLExpress;Integrated Security=True;" +
"Initial Catalog=LibraryApp";
4] Create a connection object, called Conn. Add the line below to your form and test it; your form should load, but
there will be no evidence that the database stuff is working yet. (See Below!)
SqlConnection Conn = new SqlConnection(ConnectionString);
5] Create a string object, called Query. We could read all of the User records into a record set and cycle through
them. If we had thousands of records, this would take both time and memory. If this were a single user application
with a small number of records, this might be ok.
We are designing an application strategy that will be extremely fast for small and large data sets. We are going to
read only a single record at a time. We are about to design a record to read the Crisanto record (ID = 1) from our
Users table. Add the line below to your form and test it; your form should load, but there will be no evidence that the
database stuff is working yet. (See Below!)
String Query = "Select * From Users where ID = 1";
6] We have established a connection and created a query command. We are now going to create a data adapter
object, called da.
The SqlDataAdapter holds the SQL commands and connection object for reading and writing data. We are going to
initialize it by passing our SQL Query and our Connection object.
SqlDataAdapter da = new SqlDataAdapter(Query, Conn);
The code above creates a new SqlDataAdapter, da. The SQL select statement specifies what data will be read into a
DataSet. The connection object, Conn, has already been instantiated, but not opened. As you can see in the diagram
above, It is the SqlDataAdapter's responsibility to open and close the connection when Fill and Update method are
called.
Add the line below to your form and test it; your form should load, but there will be no evidence that the database
stuff is working yet.
7] The results of our query command are going to be returned to the data table in our application. We are now going
to create a data table object, called dt. Add the line below to your form and test it; your form should load, but there
will be no evidence that the database stuff is working yet. (See Below!)
DataTable dt = new DataTable();
8] Once we have created the data table, we can use the data adapter to fill it with data in accordance with our
diagram above. Add the line below to your form and test it; your form should load, but there will be no evidence that
the database stuff is working yet. (See Below!)
da.Fill(dt);
9] We now have data and can display it! Add the line below to your form and test it!
MessageBox.Show(dt.Rows[0]["First"].ToString());
Your form should load and the message box should display the following: (See Below!)
1] In accordance with ConnectionStrings.com, let us define our Connection String to load the Library database on
Net1\SQLExpress for user student whose password is student. Note the need to use the \\ escape sequence in the
connection string. Create a string object, called ConnectionString, and fill it in accordance with your SQL Server
Name. Add the line below to your form and test it; your form should load, but there will be no evidence that the
database stuff is working yet. (See Below!)
String ConnectionString = "Data Source=NET1\\SQLEXPRESS;Initial Catalog=LibraryApp;" +
"Persist Security Info=True;User ID=student; Pwd=student";
2] Your form should once again load and the message box should display the following: (See Below!)
3] Your Users.cs form should work equally well. The compelte code is shown below!
1] As we begin to modularize our code, we will find that we are going to use the Conn object and the dt object in a
number of modules. Rather than create multiple connections, or pass it, let us make them available to the entire
form. Declare Conn and dt as shown below. Add the other variables as well; we shall use them later.
public partial class Users : Form
{
long RecNo, NoRecords;
SqlConnection Conn;
DataTable dt;
2] A number of the functions in this application can be re-used in multiple applications if generalized a bit. Include the
code for functions WindowsAuthenticationConnection and SQLAuthenticationConnection immediately below
the declarations for Conn and dt (above)..
3] Test function WindowsAuthenticationConnection with the code below. Substitute your SQLServer!
3] Test function SQLAuthenticationConnection with the code below. Substitute your SQLServer!
private void Users_Load(object sender, EventArgs e)
{
SQLAuthenticationConnection("NET1\\SQLEXPRESS", "LibraryApp", "student", "student");
String Query = "Select * From Users where ID = 1";
SqlDataAdapter da = new SqlDataAdapter(Query, Conn);
DataTable dt = new DataTable();
da.Fill(dt);
MessageBox.Show(dt.Rows[0]["First"].ToString());
}
Create txtTrace
1] Using your mouse, drag a ListBox from the ToolBox off to the side of your Users form. Using a MessageBox to
display very much is a hassle. Name the ListBox lbTrace.
Function DisplayRecord
1] We are generally going to have only one record in our DataTable dt; it will be located at Function
DisplayRecord shall be used to display the data table field name and content of the the first, and only, record in our
DataTable. It is generic and will work for other tables as well. Add the following utility function to your application.
4] As we move to the top, next, previous, and bottom records, it is essential that we be able to display the DataTable
information.
Function TableLength
1] Add generic Function TableLength to your Users.cs form. If we are going to create a button to go to the Next
Record, it will be essential that we know how many records are in the table. Note that this number might continually
change in a multi-user (concurrent) database application.
2]
4] Note that the value in the CNoRecords variable was calculated this time; in the previous section, it was simply
assigned..
Function FillFormVariables
1] Add Function FillFormVariables to your Users.cs form. The responsibility of FillFormVariables is to fill the User
Form variables with the data from record 0 in the DataTable Record. This function is non-generic, but there will be a
similar function on other forms, such as Books.cs.
2]
Function FillDataTable
1] Add Function FillDataTable to your Users.cs form. The responsibility of FillFormVariables explicitly return a
DataTable that has been filled with the passed Query.
Button btnClose
1] In accordance with our other tutorials, the ViewUser MenuStrip control seen below
2] Should you choose to close our exiting user form by clicking the X in the top right corner
you would get an error message next time you tried to open it from the main Application form. Even though I have
included this code in previous tutorials, I am going to include the code it agian below. Add the code to remove the
close functionality from your User form.
//================================================================================//
//
CreateParams
//
//================================================================================//
// Purpose: Block of code to disable the close box on a form and yet control
//
//
miniize and maximize functionality.
//
//
//
// Written By : Dr. Thomas E. Hicks
Environment : .NET 2005
//
//
Date : 3/1/2008
Language : C#
//
//================================================================================//
private const int CS_NOCLOSE = 0x200;
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CS_NOCLOSE;
return cp;
}
}
1] Add the diagnostic Function DisplayFormVariables to your Users.cs form. This function will send a copy of all
Form Variables to txtTrace. It should prove to be a valuable diagnostic routine when we begin to have problems with
our navigation functions later in this tutorial.
//================================================================================//
//
DisplayFormVariables
//
//================================================================================//
// Purpose: Display the Form Variables in the listbox called lbTrace.
//
//
//
// Written By : Dr. Thomas E. Hicks
Environment : .NET 2005
//
//
Date : 3/1/2008
Language : C#
//
//================================================================================//
public void DisplayFormVariables()
{
lbTrace.Items.Add("-----------------------------------------------------");
lbTrace.Items.Add("
Form Variables
");
lbTrace.Items.Add("-----------------------------------------------------");
lbTrace.Items.Add("TableName.........= " + TableName.ToString());
lbTrace.Items.Add("PrimaryKey........= " + PrimaryKey.ToString());
lbTrace.Items.Add("OrderBy...........= " + OrderBy.ToString());
lbTrace.Items.Add("NoRecords.........= " + NoRecords.ToString());
lbTrace.Items.Add("RecNo.............= " + RecNo.ToString());
lbTrace.Items.Add("OrderBy...........= " + OrderBy.ToString());
lbTrace.Items.Add("txtFirst..........= " + txtFirst.Text);
lbTrace.Items.Add("txtMI.............= " + txtMI.Text);
lbTrace.Items.Add("txtLast...........= " + txtLast.Text);
lbTrace.Items.Add("txtMajorID........= " + txtMajorID.Text);
lbTrace.Items.Add("txtAdministrator..= " + txtAdministrator.Text);
lbTrace.Items.Add("txtUserName.......= " + txtUserName.Text);
lbTrace.Items.Add("txtPassword...... = " + txtFirst.Text);
lbTrace.Items.Add("dt->[ID]..........=" + dt.Rows[0]["ID"].ToString());
lbTrace.Items.Add("dt->[Deleted].....=" + dt.Rows[0]["Deleted"].ToString());
lbTrace.Items.Add("dt->[FullName]....=" + dt.Rows[0]["FullName"].ToString());
lbTrace.Items.Add("-----------------------------------------------------");
}
Function LoadToolTips
1] Using your mouse, drag a ToolTip from the ToolBox to your User.cs form. Name the ToolTip toolTip1.
2] Add function LoadToolTips to your User.cs form.
public void LoadToolTips()
{
toolTip1.SetToolTip(btnA, "Go To The First User Whose Last Name Starts With An 'A'");
toolTip1.SetToolTip(btnB, "Go To The First User Whose Last Name Starts With An 'B'");
toolTip1.SetToolTip(btnC, "Go To The First User Whose Last Name Starts With An 'C'");
toolTip1.SetToolTip(btnD, "Go To The First User Whose Last Name Starts With An 'D'");
toolTip1.SetToolTip(btnE, "Go To The First User Whose Last Name Starts With An 'E'");
toolTip1.SetToolTip(btnF, "Go To The First User Whose Last Name Starts With An 'F'");
toolTip1.SetToolTip(btnG, "Go To The First User Whose Last Name Starts With An 'G'");
toolTip1.SetToolTip(btnH, "Go To The First User Whose Last Name Starts With An 'H'");
toolTip1.SetToolTip(btnI, "Go To The First User Whose Last Name Starts With An 'I'");
toolTip1.SetToolTip(btnJ, "Go To The First User Whose Last Name Starts With An 'J'");
toolTip1.SetToolTip(btnK, "Go To The First User Whose Last Name Starts With An 'K'");
toolTip1.SetToolTip(btnL, "Go To The First User Whose Last Name Starts With An 'L'");
toolTip1.SetToolTip(btnM, "Go To The First User Whose Last Name Starts With An 'M'");
toolTip1.SetToolTip(btnN, "Go To The First User Whose Last Name Starts With An 'N'");
toolTip1.SetToolTip(btnO, "Go To The First User Whose Last Name Starts With An 'O'");
toolTip1.SetToolTip(btnP, "Go To The First User Whose Last Name Starts With An 'P'");
toolTip1.SetToolTip(btnQ, "Go To The First User Whose Last Name Starts With An 'Q'");
toolTip1.SetToolTip(btnR, "Go To The First User Whose Last Name Starts With An 'R'");
toolTip1.SetToolTip(btnS, "Go To The First User Whose Last Name Starts With An 'S'");
toolTip1.SetToolTip(btnT, "Go To The First User Whose Last Name Starts With An 'T'");
toolTip1.SetToolTip(btnU, "Go To The First User Whose Last Name Starts With An 'U'");
toolTip1.SetToolTip(btnV, "Go To The First User Whose Last Name Starts With An 'V'");
toolTip1.SetToolTip(btnW, "Go To The First User Whose Last Name Starts With An 'W'");
toolTip1.SetToolTip(btnX, "Go To The First User Whose Last Name Starts With An 'X'");
toolTip1.SetToolTip(btnY, "Go To The First User Whose Last Name Starts With An 'Y'");
toolTip1.SetToolTip(btnZ, "Go To The First User Whose Last Name Starts With An 'Z'");
toolTip1.SetToolTip(btnSearch,
"Launch Search User Dialog!");
toolTip1.SetToolTip(btnAdd,
"Add A New User!");
toolTip1.SetToolTip(btnDelete,
"Delete This User!");
toolTip1.SetToolTip(btnUnDelete,
"Undelete Users!");
toolTip1.SetToolTip(btnEdit,
"Edit This User!");
toolTip1.SetToolTip(btnPrint,
"User Reports & PrintOut Options!");
toolTip1.SetToolTip(btnNextRight,
"Go To The LoadNextRecord User!");
toolTip1.SetToolTip(btnPreviousRight, "Go To The LoadPreviousRecord User!");
toolTip1.SetToolTip(btnTopRight,
"Go To The First User!");
toolTip1.SetToolTip(btnBottomRight, "Go To The Last User!");
toolTip1.SetToolTip(btnNextLeft,
"Go To The LoadNextRecord User!");
toolTip1.SetToolTip(btnPreviousLeft, "Go To The LoadPreviousRecord User!");
toolTip1.SetToolTip(btnTopLeft,
"Go To The First User!");
toolTip1.SetToolTip(btnBottomLeft,
"Go To The Last User!");
toolTip1.SetToolTip(btnClose,
"Close This Form!");
}
3] Test Function LoadToolTips with the following:
private void Users_Load(object sender, EventArgs e)
{
TableName = "Users";
PrimaryKey = "ID";
OrderBy = "FullName";
WindowsAuthenticationConnection("NET1\\SQLEXPRESS", "LibraryApp");
RecNo = 1;
NoRecords = TableLength(TableName);
dt = FillDataTable("Select * From Users where ID = 2");
FillFormVariables();
DisplayFormVariables();
LoadToolTips();
}
1] Suppose we
do the Query
: Select *
From
Users. The
records will be
displayed in
Physical Order.
The users has
an auto
incremented
ID field that
helps to
confirm this in
the snapshot
below; note
that this
primary key
helps to
confirm the
order. If one
were to cycle
through the
records in
which the ID =
1, ID =2, ID
=3, etc <==
this would be
referred to as
Physical Order.
2] Suppose we do the Query : Select * From Users Order By FullName. The records will be displayed in Logical
Order. Note that this order is different than the Physical Order above. If one were to cycle through the records in
which the ID = 8, ID = 9, ID = 11, etc but the critical issue here is that cycling through the records would provide
Agoston, Akers, Aldana, etc. (because of the Order By) <== this would be referred to as logical order.
3] Most applications display data in some type of Logical Order. It is critical that our Next and Previous buttons cycle
through our records in Logical Order.
1] Different databases enhance/enrich the standard query language by providing additional functionality; the Limit
functionality provided by MySQL is such an enhancement. Suppose we do the Query : Select * From Users Order
By FullName Limit 3,5 (See Below!)
2] The Query : Select * From Users Order By FullName Limit 3,5 would display 5 records in logical order starting with the RecNo 3. The first record is RecNo = 0.
3] The Query : Select * From Users Order By FullName Limit 0,1 would display RecNo = 0.
4] The Query : Select * From Users Order By FullName Limit 4,1 would display RecNo = 4.
5] Limit makes it extremely easy to cycle through records in a MySQL database using both web pages or stand-alone
applications. The limit provides a truly generic solution that will work with any table in any order.
1] After hours of research, I have not been able to find a truly generic solution for MSSQL. I do have something that
will work for tables that contain a Primary Key. There are lots of hack solutions on the Internet, but I think the
solution below offers the most generic approach for MSSQL.
2] The table must have a Primary Key. The PrimaryKey for the Users table is ID.
3] Below you can see the results of the Query =
SELECT TOP 5 *
FROM Users
WHERE [ID] NOT IN
(SELECT TOP 3 [ID]
FROM [Users]
ORDER BY FullName)
ORDER BY FullName
4] This much more complicated MSSQL Query would also display 5 records in logical order - starting with the RecNo
3. The first record is RecNo = 0.
5] The Query to display the fifth logical record, RecNo 4, is seen below.
Function FillTableRecord
1] The question becomes, "how do we extrapolate what we have seen above into a usable generic function?"
2] In the first FillTableWithRecord function I wrote, I passed four arguments:
public DataTable FillTableWithRecord (long RecNo, String TableName, String PrimaryKey, String OrderBy)
3] The user can use the OrderBy ComboBox to control the display order on the form. his function was effective and I
called it many times in the User form, but I kept passing it the same information over and over. In order to simplify
this tutorial, I have declared seven variables that shall be available to all of the functions on the Users form.
5] Because the TableName, PrimaryKey, and OrderBy are globally available, I have written a simplified
FillTableWithRecord function that is passed only one argument:
public DataTable FillTableWithRecord (long RecNo)
6] Add function FillTableWithRecord to your application
Function LoadNextRecord
1] The purpose of LoadNextRecord is to load the next undeleted logical record. When we get to last logical record, it
will be the responsibility of LoadNextRecord to wrap around and proceed to the next undeleted record starting from
record 0.
2] NoRecords is repeatedly filled because any user on a concurrent system might add new records at any time. Add
function LoadNextRecord to your project.
4] Run your application and cycle all the way through the records. Open the Users table and set Deleted to T/t for
Steven, Michael, and John. (See Below!)
5] Cycle all the way through the records again; note that 2, 3, and 5 are skipped.
Function LoadPreviousRecord
1] The purpose of LoadPreviousRecord is to load the previous undeleted logical record. When we get to first logical
record, it will be the responsibility of LoadPreviousRecord to wrap around and proceed to the previous undeleted
record starting from last logical record.
2] NoRecords is repeatedly filled because any user on a concurrent system might add new records at any time. Add
function LoadPreviousRecord to your project.
4] Run your application and cycle all the way through the records; note that 2, 3, and 5 are still skipped.
Function LoadFirstRecord
1] The purpose of LoadFirstRecord is to load the first undeleted logical record. If the first record is deleted, then
proceed to the next record.. Add function LoadFirstRecord to your project.
and btnPreviousTopLeft.
Function LoadLastRecord
1] The purpose of LoadLastRecord is to load the last undeleted logical record. If the last record is deleted, then
proceed to the previoous record.. Add function LoadLastRecord to your project.
Function SetRecNo
1] Filters and OrderBy increase the difficulty level of the navigation buttons we have completed thus far. The purpose
of SetRecNo is to adjust the RecNo appropriately as one changes the OrderBy ComboBox.Resetting the RecNo
properly for ordered lists makes this the most challenging function in the tutorial.
2] Add function SetRecNo to your project.
Function LoadFirstLetterRecord
1] The purpose of LoadFirstLetterRecord is to load the first undeleted logical record whose FieldName begins with the
Letter. If that record is deleted or not there then proceed to the next record; wrap around if necessary. Note that this
function uses the SetRecNo function above.
2] The process of searching for the first record whose starting letter matches the FullName, it is necessary to
temporarily change the order to the FullName; the user's chosen order is returned upon completion.
3] Add function LoadFirstLetterRecord to your project.
4] Add a call to LoadFirstLetterRecord for each and every one of the 26 buttons below. (See Below!)
1] Double click on your OrderBy combo box. The ComboBox to change the OrderBy is pretty straight forward. Include
the code in your application..
Project TU
1] The TU Project that is used for this tutorial is found below; place it at the root of drive C:\
TU-4.zip
1] Just a quick check. Start Microsoft SQL Server or SQL Server Express. Note that our server, to which we shall
connect, is NET1\SQLEXPRESS (See Below!)
2] It is our intention to connect to fill our faculty form with the Dr. Maurice Eggen information ID = 1. (See Below!)
1] Visual Studio offers many ways to connect data to forms. I am first going to walk
through the technique often used by developers and then going to come back and show
some of the other options.
2] If you take a look at the Server Explorer, you will see that Net1 currently has no data
connectors. We shall add one shortly!
3] According to the Microsoft site:
Visual Studio 2005 introduces the concept of Data Sources for a project. A Data Source
represents the data that is available to an application. This data does not necessarily come
from a databasethe Data Source Configuration Wizard that you use to define a Data Source
allows you to get the data from three different sources:
A. DatabaseThis can be either a server-based database such as SQL Server or Oracle,
or a file-based database such as Access or SQL Server Express. Visual Studio
automatically generates typedDataSets and other classes and adds them to your
project.
B. ObjectAny object with public properties can be the source of the data. It is not
necessary to implement any special interfaces.
C. Web serviceCreating a Data Source from a Web service creates objects that
correspond to the type of data that is returned from the Web service.
The purpose of the Data Source is twofold. First of all, it is a way to make it easier to specify,
design, and generate strongly-typed classes that represent the application's data. Secondly, it
provides a flexible, but uniform, mechanism for building rich and highly functional WinForm
and WebForms user interfaces very quickly.
A database Data Source is the combination of a strongly-typed DataSet and one or more
pairs of strongly-typed DataTables and TableAdapters. A typed DataSet is a generated
class that is derived from the .NET Framework's generic DataSet class, but has a defined
schema, along with properties and methods that are specific to that schema.
4] We have a Microsoft SQL Server; we plan to connect to the TU database.
5] We have a Microsoft SQL Server; we plan to connect to the TU database. We are going to use the ADO.NET data
provider as an interface between our application and the database; it acts as a middleware application.
6] ADO.NET can connect to a number of different database, but we shall concentrate on the MSSQL database. A
Connection must be established between the ADO Data Provider and the database. This connection is a two-way
connection because information will both come from and be sent to the database.
7] It will be the job of the ADO.NET Data Provider to supply one or more database tables to the application DataSet.
8] The Data Table Adapter shall supply one or more database tables to the application DataSet.
9] SQL Commands shall be used to control the transfer. SQL SELECT, INSERT, UPDATE, DELETE, etc. shall be the
basis for the logic.
1] The strategy used below is the quick and dirty, drag things to the form.
2] In order to create a DataSet, right mouse click on the TU project -> Select New Item.. (See Below!)
3] Select the DataSet template. Name the DataSet FacultyDataSet.xsd. Using the mouse, select/push
the Add button. (See Below!)
Add A TableAdapter
1] The FacultyDataSet object needs a TableAdapter in order to create a connection to the database. Using the mouse,
drag the TableAdapter from the Toolbox to your FacultyDataSet form. (See Below!)
1] Once you create a Connection, you can use it for numerous forms. The drop-down will contain a list of all of the
previous connections. Since we have no previous connections, we must push/select the NewConnection.. button.
(See Below!)
2] Select the Microsoft SQL Server data source. Using the mouse, select/push the Continue button. (See Below!)
3] Now is the time to use NET1\SQLEXPRESS; enter it for Server name: once it authenticates, you will have an
opportunity to Select the TU database in the drop down box at the bottom. (See Below!)
4] Using the mouse, select/push the Test Connection button. (See Below!)
8] This single connection will enable you to access any of the tables in
9] We are going to use SQL Statements. Select Use SQL statements. Using the mouse, select/push the Next button.
(See Below!)
1] I could have simply entered the query for Dr. Eggen's record, but I wanted to demonstrate how to use the query
builder. Using the mouse, select/push the Query Builder.. button. (See Below!)
2] Select the Faculty Table. Using the mouse, select/push the Add button. (See Below!)
3] Queries often use more than one table, but this one is going to be quite simple. Using the mouse, select/push
the Close button. (See Below!)
5] Checking the ID will allow us to enter a range of acceptable values for the ID
6] When the filter is set to =1, only Dr. Eggen's record will be pulled from the Faculty table. .
7] As the Query Builder GUI is used, the equivalent SQL is shown in the window. We could have simply entered this
query in the window at step 1. (See Below!)
8] There are a lot of equivalent forms for this query. The query I would have entered is
SELECT First, Last, ID, Gender, SpecialtyID, About
FROM Faculty
WHERE ID = 1
9] The actual query builder is shown below. It would be nice to see if this really does grab Dr. Eggen's record. Test
the query. Using the mouse, select/push the Execute Query button. (See Below!)
10] You can see the record at the bottom; it info looks great. Using the mouse, select/push the OK button. (See
Below!)
11] Using the mouse, select/push the Finish button. (See Below!)
12] Using the mouse, select/push the Finish button. (See Below!)
13] We know that the Connection was successful because the Executed Query rendered Dr. Eggen's record; we have
not yet used that data to populate our form. Execute the application and you will see the following: (See Below!)
1] Return to the Toolbox. Note that there are now components for the FacultyDataSet and FacultyTableAdapter. Using
the mouse, drag the FacultyDataSet to the Faculty Form. (See Below!)
2] Note that the FacultyDataSet object fell to a gray area at the bottom of the form; this enables it to be part of the
form without getting in the way of the form designers. Using the mouse, drag the FacultyTable Adapter to the Faculty
Form. (See Below!)
3] Note that the FacultyTableAdapter object fell to a gray area at the bottom of the form; this enables it to be part of
the form without getting in the way of the form designers. (See Below!)
4] It is time to insert some code in file Faculty.cs. Including the facultyDataSet1 and the facultyTableAdapter1
automatically generated function Faculty_Load. Add the code below to that function.
5] Faculty_Load calls a function, called FillRecord. Add Function FillRecord immediately below the Faculty_Load
function. The code is seen below:.
6] If our query had selected multiple records, the Function FillRecord could be used to pace other records in the
form. Our query has only one record, record 0. We are passing Rows[0] into the form. As a result, you can see the
following when you execute the form:
7] As a result of the drag and drop, you can see TU Components have been automatically added to the ToolBox; this
makes it easier to add the FacultyDataSet or the FacultyTableAdapter to other forms.
8] Once you create the Data Connector, it will be available to all other applications. You can see the TU connector in
the Server Explorer below..
1] Using the mouse, right mouse click on the TU connection and select Delete. (See Below!)
1] Using the mouse, right mouse click on the Data Connections and select Add Connection... (See Below!)
or you can hold down the Tools Menu and select Connect To Database..
2] Either entrance will enable you to enter a Server Name of NET1\SQLEXPRESS: once it authenticates, you will
have an opportunity to Select the TU database in the drop down box at the bottom. (See Below!)
3] Using the mouse, select/push the Test Connection button. (See Below!)
6] Once you create the Data Connector, it will be available to all other applications. You can see the TU Data
Connections in the Server Explorer below.
1] Let us reconfigure the FacultyDataSet to retrieve all of the Faculty records. Using the mouse, double-click
on FacultyDataSet.xsd. In order to reconfigure the SQL associated with the dataset, we need only right mouse click
on the dataset and selectConfigure. (See Below!)
2] Although we could use the Query Builder, I am simply going to modify the query in the window. Try it. Using the
mouse, select/push the Finish button. (See Below!)
3] When loaded, our form looks the same, but we transferred much more information from our server. Having this
information in the DataSet enables us to easily add some additional functionality to our form. (See Below!)
2] We are about to use these two buttons to cycle through our records. Declare an integer counter, called Pos, at the
top of your Faculty form. (See Below!)
3] The Faculty table of the TU database currently has 5 records, numbered in our facultyDataSet1 as records 0-4. I
would like the btnNext too cycle through the record set from record 0, to record 1, to record 2 to record 3 to record 4
and then back to record 0. The code for btnNext_Click can be seen below. (See Below!)
4] The Faculty table of the TU database currently has 5 records, numbered in our facultyDataSet1 as records 0-4. I
would like the btnPrevious too cycle through the record set from record 4, to record 3, to record 2 to record 1 to
record 0 and then back to record 4. The code for btnPrevious_Click can be seen below. (See Below!)
5] This is a common solution, but one riddled with inefficiency. facultyTableAdapter1.Fill downloads the entire
database table each and every time the user pushes the Previous button or the Next button.
Adding A DataGridView
1] The DataGridView container offers a way to easily display a collection of objects. Select the ContactList tab from
the Faculty form. Using the mouse, drag the DataGridView from the ToolBox to the tab. (See Below!)
Hold down the Drop-down and select Add Project Data Source. (See Below!)
3] Using the mouse, select the Database. Using the mouse, push/select the Next button.
(See Below!)
4] We shall use the TUConnectionString again. Using the mouse, push/select the Next button.
5] We are going to fill the grid with all of the Faculty data. Select the FacultyTable and check each of the fields. You
can name the DataSet if you like. Using the mouse, select/push the Finish button. (See Below!)
6] Select Dock in Parent Container. Disable Editing, Deleting, and Adding. (See Below!)
7] When you run the form, it will look like it only somewhat works! (See Below!)
8] Drag your mouse over some of the grid cells and you will see data. You are not seeing the data because of the
default color configuration. (See Below!)
9] You can play around with the various component configurations until you find a combination that is palatable.
Below you can see where I configured the DefaultCellStyle property.
10] The DataGridView makes it extremely easy to display a collection of data. As long as the collection is relatively
small, this is a neat tool. We did not have to display all of the fields in the table. (See Below!)
Project TU