Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Web App Notes 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

UNIT-2

Configuring Controls in Windows Forms


Control Class, Buttons, Text Boxes, Labels, Literals, Image Controls, Picture Box Control, Panel
Control, Combo Box Control, List Boxes, Dropdown Lists, Date Time Picker Control, Link Labels,
Check Boxes, Check Box Lists, Radio Buttons, Radio Button Lists, Rich Text Box Control, Tab
Control, Tool Strip Control, Menu Strip Control, Progress Bar, MDI Applications, MDI Parent
And MDI Child Forms, Manage Menus
Configuring Connections and Connecting to Data
What Is a Connection Object, Creating Connections in Server Explorer, Creating Connections Using
Data Wizards, Creating Connection Objects Programmatically? Opening and Closing Data
Connections.
Working with Data in a Connected Environment: Creating and Executing CommandObjects, working
with Parameters in SQL Commands.

Configuring controls in Windows Form

A Windows forms application is one that runs on the desktop


computer. A Windows forms application will normally have a
collection of controls such as labels, textboxes, list boxes, etc.

Windows Forms is a Graphical User Interface(GUI) class library


which is bundled in .Net Framework. Its main purpose is to provide
an easier interface to develop the applications for desktop, tablet, PCs.
It is also termed as the WinForms. The applications which are
developed by using Windows Forms or WinForms are known as
the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms
Applications not web applications. WinForms applications can
contain the different type of controls like labels, list boxes, tooltip etc.

Window Form Controls

Windows Forms is a Graphical User Interface(GUI) class library


which is bundled in .Net Framework. Its main purpose is to provide
an easier interface to develop the applications for desktop, tablet, PCs.
It is also termed as the WinForms. The applications which are
developed by using Windows Forms or WinForms are known as
the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms
Applications not web applications. WinForms applications can
contain the different type of controls like labels, list boxes, tooltip etc.

Creating a Windows Forms Application Using Visual Studio 2017

·       First, open the Visual Studio then Go to File -> New ->
Project to create a new project and then select the language as Visual
C# from the left menu. Click on Windows Forms App(.NET
Framework) in the middle of current window. After that give the
project name and Click OK.

Here the solution is like a container which contains the projects and
files that may be required by the program.

·       After that following window will display which will be divided


into three parts as follows:

1.    Editor Window or Main Window: Here, you will work with


forms and code editing. You can notice the layout of form which is
now blank. You will double click the form then it will open the code
for that.

2.    Solution Explorer Window: It is used to navigate between all


items in solution. For example, if you will select a file form this
window then particular information will be display in the property
window.

3.    Properties Window: This window is used to change the different


properties of the selected item in the Solution Explorer. Also, you can
change the properties of components or controls that you will add to
the forms.
You can also reset the window layout by setting it to default. To set
the default layout, go to Window -> Reset Window Layout in Visual
Studio Menu.

·       Now to add the controls to your WinForms application go


to Toolbox tab present in the extreme left side of Visual Studio. Here,
you can see a list of controls. To access the most commonly used
controls go to Common Controls present in Toolbox tab.

·       Now drag and drop the controls that you needed on created
Form. For example, if you can add TextBox, ListBox, Button etc. as
shown below. By clicking on the particular dropped control you can
see and change its properties present in the right most corner of
Visual Studio.

In the above image, you can see the TextBox is selected and its
properties like TextAlign, MaxLength etc. are opened in right most
corner. You can change its properties’ values as per the application
need. The code of controls will be automatically added in the
background. You can check the Form1.Designer.cs file present in the
Solution Explorer Window.

·       To run the program you can use an F5 key or Play button present
in the toolbar of Visual Studio. To stop the program you can use
pause button present in the ToolBar. You can also run the program by
going to Debug->Start Debugging menu in the menubar.

Control class in.net


The Control class is the base class for many of the controls you add to
an application. The Control class defines very little behavior; while it
is possible to add a Control to your application, it is far more common
to add a control that inherits from Control, such as a Button or
ListBox.
The Control class is in the System.Windows.Forms namespace. It
serves as a base class for the Windows controls you'll see, such as text
boxes. For example, here's the class hierarchy for text boxes, where
the MarshalByRefObject class is derived from the Object class, the
Component class is derived from MarshalByRefObject-all the way
through the Control class and up to the TextBox class:
Object
   MarshalByRefObject
      Component
         Control
            TextBoxBase
               TextBox

Button in C#
A Button is an essential part of an application, or software, or
webpage. It allows the user to interact with the application or
software. For example, if a user wants to exit from the current
application so, he/she click the exit button which closes the
application. It can be used to perform many actions like to submit,
upload, download, etc. according to the requirement of your
program. It can be available with different shape, size, color, etc. and
you can reuse them in different applications. In .NET Framework,
Button class is used to represent windows button control and it is
inherited from ButtonBase class. It is defined
under  System.Windows.Forms namespace. 

C# | TextBox Controls
In Windows forms, TextBox plays an important role. With the help
of TextBox, the user can enter data in the application, it can be of a
single line or of multiple lines. The TextBox is a class and it is
defined under System.Windows.Forms namespace. In C#, you can
create a TextBox in two different ways:
1. Design-Time: It is the simplest way to create a TextBox as shown
in the following steps:
 Step 1: Create a windows form. As shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp

 Step 2: Drag the TextBox control from the ToolBox and drop it on
the windows form. You can place TextBox anywhere on the
windows form according to your need.

 Step 3: After drag and drop you will go to the properties of the
TextBox control to modify the TextBox design according to your
requirement.

2. Run-Time: It is a little bit trickier than the above method. In this


method, you can create your own textbox using the TextBox class.
 Step 1 : Create a textbox using the TextBox() constructor provided
by the TextBox class.
 // Creating textbox

 TextBox Mytextbox = new TextBox();


 Step 2 : After creating TextBox, set the properties of the TextBox
provided by the TextBox class.

 // Set location of the textbox


 Mytextbox.Location = new Point(187, 51);

 // Set background color of the textbox


 Mytextbox.BackColor = Color.LightGray;

 // Set the foreground color of the textbox
 Mytextbox.ForeColor = Color.DarkOliveGreen;

 // Set the size of the textbox


 Mytextbox.AutoSize = true;

 // Set the name of the textbox


Mytextbox.Name = "text_box1";

Labels:-
Labels are one of the most frequently used C# control. We can use the
Label control to display text in a set location on the page. Label
controls can also be used to add descriptive text to a Form to provide
the user with helpful information. The Label class is defined in the
System.

Literals:-
Literals are constant values assigned to constant variables. Literals
represent fixed values that cannot be modified. Literals are a synthetic
representation of boolean, character, numeric, or string data, a
medium of expressing particular values in the program.

Image Controls:-
The PictureBox control is used for displaying images on the form.
The Image property of the control allows you to set an image both at
design time or at a runtime. Specifies whether the picture box accepts
data that a user drags on it. Gets or sets the path or the URL for the
image displayed in the control.
The following code snippet creates a PictureBox, sets its width and
height and adds control to the Form by calling Controls.Add()
method.
C# Code

1. PictureBox imageControl = newPictureBox();  
2. imageControl.Width = 400;  
3. imageControl.Height = 400;  
4. Controls.Add(imageControl);  
5. The output looks like Figure 1 where an image is displayed.

6.

Panel Control In C#:-


The Panel Control is a container control to host a group of similar
child controls. One of the major uses I have found for a Panel Control
is when you need to show and hide a group of controls. Instead of
show and hide individual controls, you can simply hide and show a
single Panel and all child controls.

Creating a Panel
We can create a Panel Control using the Forms designer at design-
time or using the Panel class in code at run-time.
Design-time
To create a Panel Control at design-time, you can drag and drop a
Panel Control from the Toolbox to a Form in Visual Studio. After you
dragging and dropping a Panel Control to the Form, the Panel looks
like Figure 1. 
Once a Panel is on the form, you can move it around and resize it
using the mouse and set its properties and events.

 
Figure 1
The following code snippet creates a Panel Control object.

1. Panel dynamicPanel = newPanel( ); 

In the next step, you may set the properties of a Panel Control. 
The following code snippet sets the location, size and Name
properties of a Panel.

1. dynamicPanel.Location = new System.Drawing.Point(26, 12);  
2. dynamicPanel.Name = "Panel1";  
3. dynamicPanel.Size = new System.Drawing.Size(228, 200);  
4. dynamicPanel.TabIndex = 0;  

ComboBox in C#:-
In Windows Forms, ComboBox provides two different features in a
single control, it means ComboBox works as both TextBox and
ListBox. In ComboBox, only one item is displayed at a time and the
rest of the items are present in the drop-down menu. The ComboBox
is a class in C# and defined
under System.Windows.Forms Namespace.

Property Description

BackColor This property is used to set the background


color for the ComboBox control.

DropDownHeight This property is used to set the height in pixels


of the drop-down portion of the ComboBox
control.

DropDownStyle This property is used to set a value specifying


the style of the ComboBox control.

DropDownWidth This property is used to set the width of the


drop-down portion of a ComboBox control.

Font This property is used to set the font of the text


displayed by the ComboBox control.

ForeColor This property is used to set the foreground


color of the ComboBox control.

Height This property is used to set the height of the


ComboBox control.

Items This property is used to get an object


representing the collection of the items
contained in this ComboBox control.
MaxDropDownItems This property is used to set the maximum
number of items to be shown in the drop-down
portion of the ComboBox control.

MaxLength This property is used to set the number of


characters a user can type into the ComboBox
control.

Name This property is used to set the name of the


ComboBox control.

SelectedItem This property is used to set currently selected


item in the ComboBox.

Size This property is used to set the height and


width of the ComboBox control.

Sorted This property is used to set a value indicating


whether the items in the combo box are sorted.

Text This property is used to set the text associated


with this ComboBox control.

Visible This property is used to set a value indicating


whether the control and all its child controls
are displayed.

Important Events

Event Description

Click This event occur when the ComboBox


control is clicked.

DragDrop This event occur when a drag-and-drop


operation is completed.

DropDown This event occur when the drop-down


portion of a ComboBox is shown.

DropDownClosed This event occur when the drop-down


portion of the ComboBox is no longer
visible.

DropDownStyleChanged This event occur when the


DropDownStyle property has changed.

Leave This event occur when the input focus


leaves the ComboBox control.

MouseClick This event occur when the ComboBox


control is clicked by the mouse.

MouseDoubleClick This event occur when the ComboBox


control is double clicked by the mouse.

MouseDown This event occur when the mouse pointer


is over the ComboBox control and a
mouse button is pressed.

MouseEnter This event occur when the mouse pointer


enters the ComboBox control.

MouseHover This event occur when the mouse pointer


rests on the ComboBox control.

SelectedIndexChanged This event occur when the SelectedIndex


property has changed.
ListBox :-

In Windows Forms, ListBox control is used to show multiple


elements in a list, from which a user can select one or more elements
and the elements are generally displayed in multiple columns. The
ListBox class is used to represent the windows list box and also
provide different types of properties, methods, and events. It is
defined under System.Windows.Forms namespace. The ListBox class
contains three different types of collection classes, i.e.

 ListBox.ObjectCollection: This class holds all the elements


contained in the ListBox control.
 ListBox.SelectedObjectCollection: This class holds a collection of
the selected items which is a subset of the items contained in the
ListBox control.
 ListBox.SelectedIndexCollection: This class holds a collection of
the selected indexes, which is a subset of the indexes of
the ListBox.ObjectCollection and these indexes specify elements
that are selected.

DropDownList control:-

The DropDownList control is asp.net web server control. we can use


dropdownlist control for hold group of items. The dropdownlist
control is used to store the multiple items and allow user to select only
one item from it. The dropdownlist control is also known as combo
box control.

DateTimePicker:-

In Windows Forms, the DateTimePicker control is used to select and


display the date/time with a specific format in your form. The
FlowLayoutPanel class is used to represent windows
DateTimePicker control and also provide different types of
properties, methods, and events. It is defined
under System.Windows.Forms namespace. You can create two
different types of DateTimePicker, as a drop-down list with a date
represented in the text, or as a calendar which appears when you
click on the down-arrow next to the given list.
1. Design-Time: It is the easiest way to create a DateTimePicker
control as shown in the following steps:
 Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp


 Step 2: Next, drag and drop the DateTimePicker control from the
toolbox to the form as shown in the below image:

 Step 3: After drag and drop you will go to the properties of the
DateTimePicker to modify DateTimePicker according to your
requirement.

Link Labels Control c#:-


A LinkLabel control is a label control that can display a hyperlink. A
LinkLabel control is inherited from the Label class so it has all the
functionality provided by the Windows Forms Label control.
LinkLabel control does not participate in user input or capture mouse
or keyboard events.
Run-time
LinkLabel class represents a hyperlink Label control. We simply
create an instance of LinkLabel class, set its properties and add this it
to the Form controls.
In the first step, we create an instance of the LinkLabel class. The
following code snippet creates a LinkLabel control object.
LinkLabel dynamicLinkLabel = newLinkLabel();
In the next step, we set properties of a LinkLabel control. The
following code snippet sets background color, foreground color, Text,
Name, and Font properties of a LinkLabel.

1. // Set background and foreground  
2. dynamicLinkLabel.BackColor = Color.Red;  
3. dynamicLinkLabel.ForeColor = Color.Blue;  
4. dynamicLinkLabel.Text = "I am a Dynamic LinkLabel";  
5. dynamicLinkLabel.Name = "DynamicLinkLabel";  
6. dynamicLinkLabel.Font = newFont("Georgia", 16);  

CheckBox in C#:-

The CheckBox control is the part of windows form which is used to


take input from the user. Or in other words, CheckBox control
allows us to select single or multiple elements from the given list or
it can provide us options like yes or no, true or false, etc. It can be
displayed as an image or text or both. The CheckBox is a class and
defined under System.Windows.Forms namespace.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApp5 {
 
public partial class Form1 : Form {
 
    public Form1()
    {
        InitializeComponent();
    }
 
    private void Form1_Load(object sender, EventArgs e)
    {
        // Creating and setting the properties of label
        Label l = new Label();
        l.Text = "Select Status:";
        l.AutoSize = true;
        l.Location = new Point(233, 111);
        l.Font = new Font("Bradley Hand ITC", 12);
        // Adding label to form
        this.Controls.Add(l);
 
        // Creating and setting the properties of CheckBox
        CheckBox Mycheckbox = new CheckBox();
        Mycheckbox.Height = 50;
        Mycheckbox.Width = 100;
        Mycheckbox.Location = new Point(229, 136);
        Mycheckbox.Text = "Married";
        Mycheckbox.Font = new Font("Bradley Hand ITC", 12);
 
        // Adding checkbox to form
        this.Controls.Add(Mycheckbox);
 
        // Creating and setting the properties of CheckBox
        CheckBox Mycheckbox1 = new CheckBox();
        Mycheckbox1.Location = new Point(230, 198);
        Mycheckbox1.Text = "UnMarried";
        Mycheckbox1.AutoSize = true;
        Mycheckbox1.Font = new Font("Bradley Hand ITC", 12);
 
        // Adding checkbox to form
        this.Controls.Add(Mycheckbox1);
    }
}
}

Check Box Lists Control c#:-


The CheckBoxList control renders a list of check boxes. The check
boxes can be rendered horizontally or vertically. Unlike the other List
controls, a user always can select multiple items when using a
CheckBoxList control. For example, the page given below contains a
CheckBoxList control that renders its list items in two columns.

RadioButton in C#
In Windows Forms, RadioButton control is used to select a single
option among the group of the options. For example, select your
gender from the given list, so you will choose only one option among
three options like Male or Female or Transgender. In C#,
RadioButton is a class and it is defined under System.Windows.
Forms namespace. In RadioButton, you are allowed to display text,
image, or both and when you select one radio button in a group other
radio buttons automatically clear. 
 Step 1: Create a radio button using the RadioButton() constructor
is provided by the RadioButton class.
// Creating radio button
RadioButton r1 = new RadioButton();
 Step 2: After creating RadioButton, set the properties of the
RadioButton provided by the RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;

// Add text in RadioButton


r1.Text = "Intern";

// Set the location of the RadioButton


r1.Location = new Point(286, 40);

// Set Font property


r1.Font = new Font("Berlin Sans FB", 12);
 Step 3: And last add this RadioButton control to the form using
Add() method.
// Add this radio button to the form
this.Controls.Add(r1);
RichTextBox Control
In C#, RichTextBox control is a textbox which gives you rich text
editing controls and advanced formatting features also includes a
loading rich text format (RTF) files. Or in other words, RichTextBox
controls allows you to display or edit flow content, including
paragraphs, images, tables, etc. The RichTextBox class is used to
represent the windows rich text box and also provide different types
of properties, methods, and events.
It is defined under System.Windows.Forms namespace.
It does not have the same 64K character capacity limit like TextBox
control. It is used to provide text manipulation and display features
similar to word processing applications like Microsoft Word.

Step 1: Create a RichTextBox control using the RichTextBox()


constructor is provided by the RichTextBox class.
// Creating a RichTextBox control
RichTextBox box = new RichTextBox();
Step 2: After creating a RichTextBox control, set the property of
the RichTextBox control provided by the RichTextBox class.
// Setting the location
// of the RichTextBox
box.Location = new Point(236, 97);

// Setting the background


// color of the RichTextBox
box.BackColor = Color.Aqua;

// Setting the text


// in the RichTextBox
box.Text = "!..Welcome to GeeksforGeeks..!";
Step 3: And last add this RichTextBox control to the form using
the following statement:
// Adding this RichTextBox
// in the form
this.Controls.Add(box);
CODE TO MAKE RICH TEXT BOX
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp30 {
public partial class Form1 : Form {
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Creating and setting the
// properties of the label
Label lb = new Label();
lb.Location = new Point(251, 70);
lb.Text = "Enter Text";

// Adding this label in the form


this.Controls.Add(lb);

// Creating and setting the


// properties of the RichTextBox
RichTextBox box = new RichTextBox();
box.Location = new Point(236, 97);
box.BackColor = Color.Aqua;
box.Text = "!..Welcome to Coding world..!";

// Adding this RichTextBox in the form


this.Controls.Add(box);
}
}
}
Tab Control:-
Windows TabControl is a useful control that allows you display
multiple dialogs tabs on a single form by switching between the tabs.
A tab acts as another Form that can host other controls. Figure 1
shows an example of TabControl in Visual Studio .NET, which allows
you to switch among multiple files using the tabs.

Adding a TabControl to Form


The simplest way to create a TabControl is using Visual Studio .NET.
I create a Windows Form application using Visual Studio .NET and
add a TabControl from Toolbox to the Form by dragging the
TabControl to the Form.
Understanding the TabControl and TabPage class 
A TabControl is a collection of tab pages and a tab page is the actual
control that hosts other child controls. TabPage class represents a tab
page.
TabControl class represents a TabControl. This class provides
members (properties, methods, and events) to work with the
TabControls. Table 1 lists the TabControl properties.
Property  Description
Alignment Area of the control where the tabs are aligned.
Appearance Visual appearance of the control's tabs.
DrawMode A way that the control's tab pages are drawn.
Value indicating whether the control's tabs change in
HotTrack
appearance when the mouse passes over them.
ImageList The images to display on the control's tabs.
ItemSize Size of the control's tabs.
A value indicating whether more than one row of tabs
Multiline
can be displayed.
Amount of space around each item on the control's tab
Padding
pages. 
Returns the number of rows that are currently being
RowCount
displayed in the control's tab strip.
SelectedIndex The index of the currently-selected tab page.
SelectedTab  Currently selected tab page.
ShowToolTip The value indicating whether a tab's ToolTip is shown
s when the mouse passes over the tab.
SizeMode The way that the control's tabs are sized.
TabCount Number of tabs in the tab strip.
TabPages Returns the collection of tab pages in this tab control.
Adding TabPage to a TabControl
 
Now I will add few tabs to the TabControl with the help of Properties
window of TabControl. The Properties window has a property called
TabPages, which is a collection of TabPage controls (see Figure 2). A
TabPage represents a page of the TabControl that can host child
controls.

Figure 2. TabPages property of TabControl


Now if you click on TabPages property in Property window, it
launches TabPage Collection Editor (see Figure 3) where you can add
a new page or remove existing pages by using Add and Remove
buttons. You can also set the properties of pages by using the right
side properties grid. As you can see from Figure 3, I add two pages
and set their properties. 
Figure 3. Adding Tab pages to a TabControl
After adding two pages to TabControl, the final Form looks like
Figure 4.
Figure 4. A Form with two Tab pages
Adding and Removing a TabPage to TabControl Programmatically
You can add and remove Tab pages to a TabControl using the
TabControl.TabPages.Add and TabControl.TabPages.Remove
methods. The following code snippet adds a new page to the
TabControl programmatically:

1. TabPage newPage = new TabPage("New Page");  
2. tabControl1.TabPages.Add(newPage);  

After adding the page, the new TabControl would look like Figure 5.
Figure 5. Adding a Tab page programmatically.
The Remove method of TabPageCollection class (through
TabControl.TabPages) removes a page by name or index from the
page collection. The following code snippet removes "New Page"
from the collection:

1. TabPage newPage = new TabPage("New Page");  
2. tabControl1.TabPages.Remove(newPage);  

The RemoveAll method removes all the pages from the collection.

Adding Controls to a TabPage


Adding controls to a TabPage is similar to adding controls to a Form.
Make a page active in the Form Designer and drag and drop controls
from Toolbox to the page. I add a Label, a TextBox, and a Button
control to Settings page of TabControl and change their properties.
The final page looks like Figure 6.

Figure 6. Adding controls to a Tab page


Controls are added to a page by using TabPage.Controls.Add method.
Now if you see the code generated by the designer, you will notice the
following code:

1. this.SettingsPage.Controls.Add(this.BrowseBtn);  
2. this.SettingsPage.Controls.Add(this.textBox1);  
3. this.SettingsPage.Controls.Add(this.label1);  

ToolStrip Control In C#
ToolStrip control provides functionality of  Windows toolbar controls
in Visual Studio 2010. ToolStrip class represents a ToolStrip control
in Windows Forms and serves as a base class of MenuStrip,
StatusStrip, and ContextMenuStrip classes.
We can create a ToolStrip control at design-time using Visual Studio
designer or using the ToolStrip class at run-time.
A ToolStrip control is nothing but a container without adding its child
controls. A ToolStrip control is capable of hosting Button, Label,
SplitButton, DropDownButton, Separator, ComboBox, TextBox and
ProgressBar controls.

MenuStrip In C#
We can create a MenuStrip control using a Forms designer at design-
time or using the MenuStrip class in code at run-time or dynamically.
To create a MenuStrip control at design-time, you simply drag and
drop a MenuStrip control from Toolbox to a Form in Visual Studio.
Creating a MenuStrip
We can create a MenuStrip control using a Forms designer at design-
time or using the MenuStrip class in code at run-time or dynamically.
To create a MenuStrip control at design-time, you simply drag and
drop a MenuStrip control from Toolbox to a Form in Visual Studio.
After you drag and drop a MenuStrip on a Form, the MenuStrip1 is
added to the Form and looks like Figure 1. Once a MenuStrip is on
the Form, you can add menu items and set its properties and events.
C# ProgressBar Control

A progress bar is a control that an application can use to indicate the


progress of a lengthy operation such as calculating a complex result,
downloading a large file from the Web etc.
ProgressBar controls are used whenever an operation takes more than
a short period of time. The Maximum and Minimum properties define
the range of values to represent the progress of a task.

 Minimum : Sets the lower value for the range of valid values for
progress.

 Maximum : Sets the upper value for the range of valid values for
progress.

 Value : This property obtains or sets the current level of


progress.

By default, Minimum and Maximum are set to 0 and 100. As the task
proceeds, the ProgressBar fills in from the left to the right. To delay
the program briefly so that you can view changes in the progress bar
clearly.

Building MDI WinForms Application using C#


Implementing an MDI Form

The Multiple-Document Interface (MDI) is a specification that


defines a user interface for applications that enable the user to
work with more than one document at the same time under
one parent form (window).

Visualize the working style of an application in which you are


allowed to open multiple forms in one parent
container window, and all the open forms will get listed under
the Windows menu.  Whereas having an individual window for
each instance of the same application is termed as single
document interface (SDI); applications such as Notepad,
Microsoft Paint, Calculator, and so on, are SDI applications. SDI
applications get opened only in their own windows and can
become difficult to manage, unlike when you have multiple
documents or forms open inside one MDI interface.

Hence, MDI applications follow a parent form and child form


relationship model. MDI applications allow you to open,
organize, and work with multiple documents at the same time
by opening them under the context of the MDI parent form;
therefore, once opened, they can't be dragged out of it like an
individual form.

The parent (MDI) form organizes and arranges all the child
forms or documents that are currently open. You might have
seen such options in many Windows applications under a
Windows menu, such as Cascade, Tile Vertical, and so on.

Try It: Creating an MDI Parent Form with a Menu Bar

In this exercise, you will create an MDI form in the WinApp


project. You will also see how to create a menu bar for the
parent form, that will allow you to navigate to all the child
forms. To do so, follow these steps:
1. Navigate to Solution Explorer, select the WinApp project,
right-click, and select "Add" -> "Windows form". Change
the Name value from "Form1.cs" to "ParentForm.cs", and
click "Add".
2. Select the newly added ParentForm in the Design View.
Select the ParentForm form by clicking the form's title bar,
navigate to the Properties window, and set the following
properties:
1. Set the "IsMdiContainer" property to True (the default
value is False). Notice that the background color of the
form has changed to dark gray.
1. Set the Size property's Width to 546 and Height to 411.

 
3. Drag a MenuStrip control to the ParentForm. In the top-left
corner, you should now see a drop-down showing the text
"Type Here". Enter the text "Open Forms" in the drop-down.
This will be your main, top-level menu.
4. Now under the Open Forms menu, add a submenu by
entering the text "Win App".
5. Under the Win App submenu, enter "User Info".
6. Now click the top menu, "Open Forms", and on the right
side of it, type "Help". Under the Help menu, enter "Exit".
7. Now, click the top menu, on the right side of Help, type
"Windows".
8. Under the Windows menu, add the following options as
separate submenus: Cascade, Tile Horizontal, Tile Vertical,
and Arrange Icons. These will help in arranging the child
forms.
9. Now it's time to attach code to the submenus you have
added under the main menu Open Forms. First, you'll add
code for the submenu Win App, that basically will open the
WinApp form. In the Design View, double-click the "Win
App" submenu, that will take you to the Code View. Under
the click event, add the following code:
WinApp objWA = new WinApp();
objWA.Show();
 
10. Now to associate functionality with the User Info submenu:
double-click this submenu, and under the click event add
the following code:

UserInfo objUI = new UserInfo();


objUI.Show();
 
11. To associate functionality with the Exit submenu located
under the Help main menu, double-click "Exit", and under
the click event add the following code:

Application.Exit();
 
12. Now you have the form-opening code functionality in place,
and you are nearly set to run the application. But first, you
need to set the ParentForm as the start-up object. To do so,
open Program.cs, and modify the "Application.Run(new
UserInfo());" statement to the following:

Application.Run(new ParentForm());
 
13. Now build the solution, and run the application by pressing
F5; the MDI application will open and should look as in
Figure 1-1.
Figure 1-1. Running an MDI form application
 
14. Now if you click "Win App" and then "User Info" then both
the forms will open one by one. These forms can be opened
and dragged outside of the MDI form. This is not an
expected behavior from a MDI application, as shown in
Figure 1-2.

This issue will be addressed later in this chapter.


Figure 1-2. Running an MDI form application

How It Works

Each Windows Forms form is a class and exposes a Show()


function by an instance created for it. You use the following
code, that is creating an object and then invoking the Show()
method. This opens the other form from the MDI parent form.

This creates an instance of the WinApp form and opens it for


you:

WinApp objWA = new WinApp();


objWA.Show();

The following code creates an instance of the UserInfo form


and opens it for you:

UserInfo objUI = new UserInfo();


objUI.Show();

You close the application with the following code:

Application.Exit();

Try It: Opening an MDI Child Form Within an MDI


Application

As mentioned and shown in Figure 1-2 above, the problem is


that even though the MDI form shows a parent menu, the
forms are still able to open outside, and context is moved from
a form to another. You can try clicking the title bar of each the
open form, and you will see how you can move back and forth
with these opened forms.

In this exercise, you will overcome this problem and associate


all the forms you created earlier as MDI child forms to the main
MDI parent form you created in the previous task.
1. In the project you modified in the previous exercise, you'll
first make the WinApp form an MDI child form. To do so,
you need to set the MdiParent property of the child form's
object to the MDI parent form itself, but in the Code View.
You have already added functionality in the previous task
(opening the WinApp form); just before the line where you
are calling the Show() method, add the following code (this
code can be found under Win App menu click event):

objWA.MdiParent=this;
After adding this line, the code will appear as follows:
WinApp objWA = new WinApp();
objWA.MdiParent = this;
objWA.Show();

Note: this is a C# language keyword that represents the


current instance of the class. In this case, it refers to
ParentForm. Because you are writing this code inside
ParentForm, you can use the this keyword for the same.

Now you will make the UserInfo form an MDI child form. To
do so, you need to set the MdiParent property to the name
of the MDI parent form but in the Code View. Add the
following code as you did in the previous step (this code
can be found under the User Info menu click event):

objUI.MdiParent=this;

After adding this line, the code will appear as follows:

UserInfo objUI = new UserInfo();


objUI.MdiParent=this;
objUI.Show();

Now build the solution, and run the application by pressing


F5; the MDI application will open and should appear as
shown in Figure 1-3.

Click "Open Form" -> "Win App"; the WinApp form should
open. Again, open the main menu and click "User Info".
Both the forms should now be open inside your main MDI
parent form application, and unlike before, you will not be
able to drag these out of your MDI parent form (as shown
in Figure 1-2). Figure 1-3 shows the expected behavior of an
MDI application with opened form(s).

Figure 1-3. Opening child forms inside an MDI form


application:

Because both the forms are open inside one MDI parent, it
becomes easier to work with them, and they are not
draggable outside of the MDI parent. Switch among these
forms by clicking their title bars. Once you are done with
the forms, close the application by selecting "Help" ->
"Exit".

How It Works
As you noticed in an earlier exercise, the only issue discussed
was that child forms opened and were able to be dragged
outside. In other words, they didn't really belong to a parent
form. An MDI application is about claiming a form with a menu
bar as an MDI parent so all the child forms can open inside it.

To do so, first an object of the child form needs to be created:

WinApp objWA = new WinApp();

But before we really invoke the Show() method on the objWA,


you need to tell the object who is its parent so it operates from
within the MDI parent form. To accomplish this, you will use the
"this" keyword, that represents the current form class.

objWA.MdiParent = this;

You have an object created and its context set to a MDI parent
form, so now it's a perfect time to call the Show() method, that
will launch the form so you can work with it.

objWA.Show();

The "wa.MdiParent=this;" line tells the child form which form is


its parent. Because you want all the child forms to appear inside
ParentForm and you write the code inside the MDI parent form,
you can use the "this" keyword to represent the current object.

Set the previous suggested changes for UserInfo as well.

UserInfo objUI = new UserInfo();


objUI.MdiParent=this;
objUI.Show();

Try It: Arranging MDI Child Forms Within an MDI


Application

Multiple forms will open within one MDI window, so once you
have a few open, your MDI application will be cluttered. It's
hard to move forms around to shift your focus from one to
another. Hence, it is a prime concern to have a mechanism that
allows you to arrange the forms in an organized manner.

For example, in most applications you can arrange the forms


and then cascade them so you can see the stack of open forms.
Or you can tile them vertically or horizontally so you can see
multiple forms side by side. You can even minimize all the open
forms and arrange them as an icon.

To accomplish this, in this exercise you will add the Windows


menu as shown in Figure 1-4.
Figure 1-4. Windows menu of MDI form application to arrange
child forms

.NET's Windows Forms offers the LayoutMdi method, that takes


the MdiLayout enumeration to rearrange the child forms in an
MDI parent form. There are four modes you can arrange your
forms into: Cascade, Tile Horizontal, Tile Vertical, and
ArrangeIcons.
1. Open the ParentForm in the Design View, and click the
Windows menu, as shown in Figure 1-4.
2. Double-click the first option, Cascade, under Windows, and
it will take you to its click event. Add the following code:
LayoutMdi(MdiLayout.Cascade);
 
3. Double-click Tile Horizontal, and in the Code View under
the click event, add the following code:

LayoutMdi(MdiLayout.TileHorizontal);
 
4. Double-click the Tile Vertical, and in the Code View under
the click event, add the following code:

LayoutMdi(MdiLayout.TileVertical);
 
5. Double-click Tile Vertical, and in the Code View under the
click event, add the following code:

LayoutMdi(MdiLayout.ArrangeIcons);
 
6. Now build the solution, and run the application by pressing
F5; the MDI application will open. After it opens, go to the
Open Forms menu and click Win App and User Info one by
one. It is important to have at least two forms open in the
MDI parent form. Now go to the Windows menu and try the
available options by clicking Cascade, then Arrange Vertical,
then Arrange Horizontal, and finally Arrange Icons. When
you will try these options, Tile Vertical will show the child
forms arranged as in Figure 1-5.
Figure 1-5. Arranging (Tile Vertical) child forms in the MDI
form application
ADO.NET
ADO.NET(ActiveX Data Objects) is a module of .Net Framework
which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML.
ADO.NET consists of classes that can be used to connect,
retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and
integrated with XML classes located into System.Xml.dll.
ADO.NET has two main components that are used for accessing
and manipulating data are the .NET Framework data provider
and the DataSet.

XML Simplifies Things


 XML simplifies data sharing
 XML simplifies data transport
 XML simplifies platform changes
 XML simplifies data availability

Many computer systems contain data in incompatible formats. Exchanging data


between incompatible systems (or upgraded systems) is a time-consuming task
for web developers. Large amounts of data must be converted, and incompatible
data is often lost.

XML stores data in plain text format. This provides a software- and hardware-
independent way of storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.

With XML, data can be available to all kinds of "reading machines" like people,
computers, voice machines, news feeds, etc.
.NET Framework Data Providers
These are the components that are designed for data
manipulation and fast access to data. It provides various objects
such as Connection, Command, DataReader and
DataAdapter that are used to perform database operations.

ADO.NET DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter
provides the communication between the Dataset(A data set (or
dataset) is a collection of data. In the case of tabular data, a
data set corresponds to one or more database tables, where
every column of a table represents a particular variable, and
each row corresponds to a given record of the data set in
question.) and the Datasource.
We can use the DataAdapter in combination with the DataSet Object.
DataAdapter provides this combination by mapping Fill method, which
changes the data in the DataSet to match the data in the data source, and
Update, which changes the data in the data source to match the data in
the DataSet. That is, these two objects combine to enable both data
access and data manipulation capabilities.

The DataAdapter can perform Select , Insert , Update and Delete SQL


operations in the Data Source. The Insert , Update and Delete SQL
operations , we are using the continuation of the Select command
perform by the DataAdapter. The SelectCommand property of the
DataAdapter is a Command Object that retrieves data from the data
source. The InsertCommand , UpdateCommand ,
and DeleteCommand properties of the DataAdapter are Command
objects that manage updates to the data in the data source according to
modifications made to the data in the DataSet.

Connection Object (ADO)


A Connection object represents a unique session with a data
source. In a client/server database system, it may be equivalent
to an actual network connection to the server. Depending on
the functionality supported by the provider, some collections,
methods, or properties of a Connection object may not be
available.
With the collections, methods, and properties of
a Connection object, you can do the following:
 Configure the connection before opening it with
the ConnectionString, ConnectionTimeout,
and Mode properties. ConnectionString is the default
property of the Connection object.

 Set the CursorLocation property to client to invoke


the Microsoft Cursor Service for OLE DB, which supports
batch updates.

 Set the default database for the connection with


the DefaultDatabase property.
 Set the level of isolation for the transactions opened on the
connection with the IsolationLevel property.

 Specify an OLE DB provider with the Provider property.

 Establish, and later break, the physical connection to the


data source with the Open and Close methods.

 Execute a command on the connection with


the Execute method and configure the execution with
the CommandTimeout property.

 Manage transactions on the open connection, including


nested transactions if the provider supports them, with
the BeginTrans, CommitTrans, and RollbackTrans methods
and the Attributes property.

 Examine errors returned from the data source with


the Errors collection.

 Read the version from the ADO implementation used with


the Version property.
 Obtain schema information about your database with
the OpenSchema method.

 You can create Connection objects independently of any


other previously defined object.

 You can execute named commands or stored procedures as


if they were native methods on a Connection object

 When a named command has the same name as that of a


stored procedure, invoke the "native method call" on
a Connection object always execute the named command
instead of the store procedure.

Connect to a database
The steps in this article show how to connect to a data source
in the Visual Studio IDE. The data source can be a local
database, online data service, or a database opened from
an .mdf file. You can work directly with your data in Visual
Studio. You can execute queries, edit data, create and edit
tables and other schema properties, edit stored procedures and
functions, triggers, and so on. These functions are independent
of the programming language or .NET version you are using.

Server Explorer and SQL Server Object Explorer

You can open a connection to a database or service, or a


LocalDB database opened from an .mdf file, and view and edit
tables and data rows, by using Server Explorer or SQL Server
Object Explorer. The functionality of these windows overlaps
to some extent. The basic differences are:

Server Explorer

Installed by default in Visual Studio. Can be used to test


connections and view SQL Server databases, any other
databases that have an ADO.NET provider installed, and
some Azure services. Also shows low-level objects such as
system performance counters, event logs, and message
queues. If a data source has no ADO.NET provider, it won't
show up here, but you can still use it from Visual Studio by
connecting programmatically.

SQL Server Object Explorer

Installed with SQL Server Data Tools and visible under


the View menu. If you don't see it there, go to Programs
and Features in Control Panel, find Visual Studio, and then
select Change to re-run the installer after selecting the
check box for SQL Server Data Tools. Use SQL Server
Object Explorer to view SQL databases (if they have an
ADO.NET provider), create new databases, modify schemas,
create stored procedures, retrieve connection strings, view
the data, and more. SQL databases that have no ADO.NET
provider installed won't show up here, but you can still
connect to them programmatically.
Add a connection in Server Explorer
To create a connection to the database, click the Connect to
database icon in Server Explorer, or right-click in Server
Explorer on the Data Connections node and select Add
Connection. From here, you can open a connection to a
LocalDB database opened from an .mdf file, connect to a
database on another server, a SharePoint service, or an Azure
service.

This brings up the Add Connection dialog box. Here, we have


entered the name of the SQL Server LocalDB
instance, (localdb)\MSSqlLocalDB, which is usually installed
with Visual Studio.
If you don't have access to another database, and you don't see
LocalDB installed, you can install LocalDB through the Visual
Studio Installer, as part of the Data Storage and
Processing workload, the ASP.NET and web
development workload, or as an individual component.
See Modify Visual Studio.

MDF files

The .mdf file stands for Master Database File and is a SQL


database packaged into a file. These files have an
associated .ldf (Log Database File) that contains the logs for
that database. You can create new databases that are stored
in .mdf files by adding a Service-based Database item to your
project. See Create a database and add tables.

If you already have .mdf file in your project, you can double-


click or right-click and choose Open to open it in Server
Explorer.

To open an .mdf file that's not in your project in Visual Studio's


Server Explorer, follow these steps:

1.

In the Add connection dialog box, under Data Source,


choose Microsoft SQL Server Database File (SqlClient).

2.
3.
Use the Browse button to find and select your master
database file (.mdf file), or enter the path in the Database
filename box.

4.
5.
6.

Choose the authentication method.

7.
8.

Test the connection, and if it is successful, choose OK. A


node for the database opens in Server Explorer.

9.

Change the provider

If the data source is not what you want, click


the Change button to choose a new data source and/or a new
ADO.NET data provider. The new provider might ask for your
credentials, depending on how you configured it.

 Note

If you're using Visual Studio 2022 to connect to OLEDB or


ODBC data providers, you will need to be aware that Visual
Studio 2022 is now a 64-bit process.

This means some of the data tools in Visual Studio will not be
able to connect to OLEDB or ODBC databases using 32-bit data
providers. This includes the Microsoft Access 32-bit OLEDB data
provider as well as other third-party 32-bit providers.

If you need to maintain 32-bit applications that connect to


OLEDB or ODBC, you will still be able to build and run the
application with Visual Studio 2022. However, if you need to
use any of the Visual Studio Data Tools such as Server Explorer,
Data Source Wizard, or the DataSet Designer, you will need to
use an earlier version of Visual Studio that is still a 32-bit
process. The last version of Visual Studio that was a 32-bit
process was Visual Studio 2019.

If you plan on converting the project to be a 64-bit process you


will need to update the OLEDB and ODBC data connections to
use 64-bit data providers.

If your application uses Microsoft Access databases, and can


convert the project to 64-bit, it’s recommended that you use
the 64-bit Microsoft Access Database Engine, also called Access
Connectivity Engine (ACE). Please see OLE DB Provider for Jet
and ODBC driver are 32-bit versions only for more
information.

If you're using a third-party data provider, we recommend


connecting with your vendor to see if they offer a 64-bit
provider before converting the project to 64-bit.
Test the connection

After you have chosen the data source, click Test Connection.


If it doesn't succeed, you will need to troubleshoot based on
the vendor's documentation.
If the test succeeds, you are ready to create a data source,
which is a Visual Studio term that really means a data
model that is based on the underlying database or service.

Connect using SQL Server Object Explorer

The experience might be easier if you use SQL Server Object


Explorer, which gives you a dialog that provides more help in
finding available databases locally, on the local network, and in
your Azure subscriptions, and provides a history of recently
used choices.

To access the connect dialog from SQL Server Object


Explorer, click the toolbar button Add SQL Server.

The connect dialog comes up. Choose your local, network, or


Azure SQL server, select a database, provide credentials, and
choose Connect.
If you need to set other settings in your connection string, you
can use the Advanced link, which brings up all the settings. For
example, to connect to a LocalDB database that's based on an
MDF file, choose Advanced and then set the
property AttachDbFilename.
After you are done setting up the connection, the server and
database are shown in the SQL Server Object Explorer window.

From there, you can browse the database, write and execute
queries, edit data, stored procedures and functions, and
perform other actions directly in Visual Studio.

Next steps

If you're using the .NET Framework (not .NET Core or .NET 5 or


later), and Windows Forms or WPF, you can the Data
Sources window, for example, to set up data binding for
controls in Windows Forms and WPF Applications, see Add new
data sources. These tools are designed to enable you to rapidly
create Windows applications that need to allow users to enter,
display, and manipulate data.

If you're using .NET 5 or later, .NET Core or ASP.NET Core, you


can connect your app to the database using Connected
Services. Using Connected Services, you can easily use a local
development database, hosted by SQL LocalDB, SQL Server
running in a container, or an on-premises instance of SQL
Server, and then transition to Azure SQL Database when you're
ready to deploy to the cloud. For .NET 5 or later, .NET Core and
ASP.NET Core, you should consider using Entity Framework
Core as your database framework.

Opening and Closing Data Connections


Connections are very limited resources. They should always be handled very carefully
and should not be kept open for long time. In fact the Connection should only be
opened when it is needed and then should be closed instantly after the use. This
means that we open the connection as late as possible and release it as quickly as
possible.

The first way to ensure this is use exception handlers. We open a connection in the
try block, use it inside the try block and close it in the finally block this will ensure
that even if an unhandled error occurs, the connection will be closed in the finally
block. If we don’t use this approach and simply close the connection inside try block
itself after performing the operation and an unhandled exception occurs, the
connection will remain open until the garbage collector disposes of
the SqlConnection object. And the connection being a precious and limited resource
we should never rely on the garbage collector to close it. It should always be closed
deterministically.
SqlConnection conn = new SqlConnection("CONNECTION_STRING_HERE");

try

conn.Open();

//Perform DB operation here i.e. any CRUD operation

//Conn.Close(); //This should never be here

catch (Exception ex)

//Handle exception, perhaps log it and do the needful

finally

//Connection should always be closed here so that it will close always

conn.Close();

Command Object
 
The command object is one of the basic components of ADO .NET.
1. The Command Object uses the connection object to execute SQL queries.
2. The queries can be in the Form of Inline text, Stored Procedures or direct Table
access.
3. An important feature of Command object is that it can be used to execute
queries and Stored Procedures with Parameters.
4. If a select query is issued, the result set it returns is usually stored in either a
DataSet or a DataReader object.
Associated Properties of SqlCommand class
 
The properties associated with SqlCommand class are shown in the Table below.
 
Property Type of Description
Access
The SqlConnection object that is used by the
Connection Read/Write command object to execute SQL queries or
Stored Procedure.
Represents the T-SQL Statement or the name of
CommandText Read/Write the Stored Procedure.
 
This property indicates how the CommandText
property should be interpreted. The possible
values are:
CommandType Read/Write
1. Text (T-SQL Statement)
2. StoredProcedure (Stored Procedure Name)
3. TableDirect
This property indicates the time to wait when
executing a particular command.
 
Default Time for Execution of Command is 30
CommandTimeout Read/Write
Seconds.
 
The Command is aborted after it times out and
an exception is thrown.
 
Now, Let us have a look at various Execute Methods that can be called from a
Command Object.
 
Property Description
This method executes the command specifies and returns the
ExecuteNonQuery
number of rows affected.
The ExecuteReader method executes the command specified
ExecuteReader
and returns an instance of SqlDataReader class.
This method executes the command specified and returns the
ExecuteScalar first column of first row of the result set. The remaining rows
and column are ignored.
This method executes the command specified and returns an
ExecuteXMLReader instance of XmlReader class. This method can be used to
return the result set in the form of an XML document
 
These are quite often methods in the Command objects. Let us now see each of
these with an example
 
ExecuteNonQuery
1. The ExecuteNonQuery method is used to execute the command and return the
number of rows affected.
2. The ExecuteNonQuery method cannot be used to return the result set.
Snippets working with ExecuteNonQuery
1. public void CallExecuteNonQuery()  
2. {  
3.     SqlConnection conn = new SqlConnection();  
4.     conn.ConnectionString = ConfigurationManager.ConnectionStrings["
connString"].ConnectionString;  
5.     try  
6.     {  
7.         SqlCommand cmd = new SqlCommand();  
8.         cmd.Connection = conn;  
9.         cmd.CommandText = "DELETE FROM EMP WHERE DEPTNO = 40";  
10.         cmd.CommandType = CommandType.Text;  
11.         conn.Open();  
12.         Int32 RowsAffected = cmd.ExecuteNonQuery();  
13.         MessageBox.Show(RowsAffected + " rows affected", "Message"); 
 
14.         cmd.Dispose();  
15.         conn.Dispose();  
16.     }  
17.     catch (Exception ex)  
18.     {  
19.         MessageBox.Show(ex.Message);  
20.     }  
21. }  

Using a parameter in the SQL


Introduction
 
The SqlParameter class is found in the "System.Data.SqlClient" namespace. It is a
class of a connected architecture of the .NET framework. It represents parameters.
To work with the SqlParameter class we should have a database. In this example, I
am using a Database "student" which has a "student_detail" table. "RollNo", "Name"
and "City" are column names. I will save and retrieve records using the
SqlParameter class.  Here is a list of important properties of the SqlParameter class
which will be used in this example.
1. SqlDbType: It is used to set the SQL Server Datatypes for a given parameter.
2. ParameterName: It is used to specify a parameter name.
3. Direction: It is used for setting the direction of a SqlParameter. It is Input or
Output or both (InputOutput).
4. Size: It is used to set the maximum size of the value of the parameter.
5. Value: It is used for assigning or getting the value of the parameter.
Now, take a Windows Forms application in Visual Studio 2010. Take some UI
Controls and arrange them as shown in the figure below
 
 
Write the following code for saving a record into the database.
1. using System;  
2. using System.Collections.Generic;  
3. using System.ComponentModel;  
4. using System.Data;  
5. using System.Drawing;  
6. using System.Linq;  
7. using System.Text;  
8. using System.Windows.Forms;  
9. using System.Data.SqlClient;  
10. namespace WorkWithSqlParameterClass {  
11.     public partial class Form1: Form {  
12.         public Form1() {  
13.             InitializeComponent();  
14.         }  
15.   
16.         SqlConnection conn;  
17.         SqlCommand comm;  
18.         string connstring = "database=student;server=.;user=sa;passw
ord=wintellect";  
19.   
20.         private void btnsave_Click(object sender, EventArgs e) {  
21.             conn = new SqlConnection(connstring);  
22.             conn.Open();  
23.   
24.             comm = new SqlCommand();  
25.             comm.Connection = conn;  
26.   
27.             //Creating instance of SqlParameter  
28.             SqlParameter PmtrRollNo = new SqlParameter();  
29.             PmtrRollNo.ParameterName = "@rn"; // Defining Name  
30.             PmtrRollNo.SqlDbType = SqlDbType.Int; // Defining DataTy
pe  
31.             PmtrRollNo.Direction = ParameterDirection.Input; // Sett
ing the direction  
32.   
33.             //Creating instance of SqlParameter  
34.             SqlParameter PmtrName = new SqlParameter();  
35.             PmtrName.ParameterName = "@nm"; // Defining Name  
36.             PmtrName.SqlDbType = SqlDbType.VarChar; // Defining Data
Type  
37.             PmtrName.Direction = ParameterDirection.Input; // Settin
g the direction  
38.   
39.             //Creating instance of SqlParameter  
40.             SqlParameter PmtrCity = new SqlParameter();  
41.   
42.             PmtrCity.ParameterName = "@ct"; // Defining Name  
43.             PmtrCity.SqlDbType = SqlDbType.VarChar; // Defining Data
Type  
44.             PmtrCity.Direction = ParameterDirection.Input; // Settin
g the direction  
45.   
46.             // Adding Parameter instances to sqlcommand  
47.   
48.             comm.Parameters.Add(PmtrRollNo);  
49.             comm.Parameters.Add(PmtrName);  
50.             comm.Parameters.Add(PmtrCity);  
51.   
52.             // Setting values of Parameter  
53.   
54.             PmtrRollNo.Value = Convert.ToInt32(txtrollno.Text);  
55.             PmtrName.Value = txtname.Text;  
56.             PmtrCity.Value = txtcity.Text;  
57.   
58.             comm.CommandText = "insert into student_detail values(@r
n,@nm,@ct)";  
59.   
60.             try {  
61.                 comm.ExecuteNonQuery();  
62.                 MessageBox.Show("Saved");  
63.             } catch (Exception) {  
64.                 MessageBox.Show("Not Saved");  
65.             } finally {  
66.                 conn.Close();  
67.             }  
68.         }  
69.     }  
70. } 
Run the application.
 
Output
 

 
Fill in the form and click the "Save" button. The record will be saved to the database
and a message box will be displayed with a confirmation message.
 

 
Now we retrieve records from the database. Take another button and set its text
property as "Show". Add the following code for the "Show" button. 
1. private void btnshow_Click(object sender, EventArgs e) {  
2.     conn = new SqlConnection(connstring);  
3.     conn.Open();  
4.   
5.     comm = new SqlCommand();  
6.     comm.Connection = conn;  
7.   
8.     //Creating instance of SqlParameter  
9.     SqlParameter PmtrRollNo = new SqlParameter();  
10.     PmtrRollNo.ParameterName = "@rn"; // Defining Name  
11.     PmtrRollNo.SqlDbType = SqlDbType.Int; // Defining DataType  
12.     PmtrRollNo.Direction = ParameterDirection.Input; // Setting the 
direction  
13.   
14.     //Creating instance of SqlParameter  
15.     SqlParameter PmtrName = new SqlParameter();  
16.     PmtrName.ParameterName = "@nm"; // Defining Name  
17.     PmtrName.SqlDbType = SqlDbType.VarChar; // Defining DataType  
18.     PmtrName.Size = 30;  
19.     PmtrName.Direction = ParameterDirection.Output; // Setting the d
irection  
20.   
21.     //Creating instance of SqlParameter  
22.     SqlParameter PmtrCity = new SqlParameter("@ct", SqlDbType.VarCha
r, 20);  
23.     PmtrCity.Direction = ParameterDirection.Output; // Setting the d
irection  
24.   
25.     // Adding Parameter instances to sqlcommand  
26.   
27.     comm.Parameters.Add(PmtrRollNo);  
28.     comm.Parameters.Add(PmtrName);  
29.     comm.Parameters.Add(PmtrCity);  
30.   
31.     // Setting values of Parameter  
32.   
33.     PmtrRollNo.Value = Convert.ToInt32(txtrollno.Text);  
34.     PmtrName.Value = txtname.Text;  
35.     PmtrCity.Value = txtcity.Text;  
36.   
37.     comm.CommandText = "select @nm=name,@ct=city from student_detail 
where rollno=@rn";  
38.   
39.     try {  
40.         comm.ExecuteNonQuery();  
41.         txtname.Text = PmtrName.Value.ToString();  
42.         txtcity.Text = PmtrCity.Value.ToString();  
43.     } catch (Exception) {  
44.         MessageBox.Show("Not Found");  
45.     } finally {  
46.         conn.Close();  
47.     }  
48. } 
Run the application.
 
Output
 

 
Enter a roll number and click the "Show" button. It will show all the related
information of the student having the given roll number.
 

Windows Forms Events Lifecycle


The events in the lifecycle of a Form from the time it is launched to the
time it is closed are listed below:

 Move: This event occurs when the form is moved. Although by


default, when a form is instantiated and launched, the user does not
move it, yet this event is triggered before the Load event occurs.
 Load: This event occurs before a form is displayed for the first time.
 VisibleChanged: This event occurs when the Visible property value
changes.
 Activated: This event occurs when the form is activated in code or by
the user.
 Shown: This event occurs whenever the form is first displayed. 
 Paint: This event occurs when the control is redrawn.
 Deactivate: This event occurs when the form loses focus and is not
the active form.
 Closing: This event occurs when the form is closing.
 Closed: This event occurs when the form is being closed.

C# - Data Types
C# is a strongly-typed language. It means we must declare the type of a variable that
indicates the kind of values it is going to store, such as integer, float, decimal, text, etc.

The following declares and initialized variables of different data types.

Example: Variables of Different Data Types


string stringVar = "Hello World!!";int intVar = 100;float floatVar =
10.2f;char charVar = 'A';bool boolVar = true;
Try it

C# mainly categorized data types in two types: Value types and Reference types. Value
types include simple types (such as int, float, bool, and char), enum types, struct types,
and Nullable value types. Reference types include class types, interface types, delegate
types, and array types. Learn about value types and reference types  in detail in the next
chapter.
Validation Controls
Validation controls are an essential part of ASP.NET web development because they
help ensure the integrity of user input. When users enter information into web forms,
there is always the potential for intentional or unintentional errors. Validation controls
provide a way to check the accuracy and validity of user input before the web
application processes it.

Some of the reasons why validation controls are important in ASP.NET are:

 Preventing invalid data from being submitted: Validation controls can check for
required fields, format and type of data, and other criteria that must be met
before the data can be submitted to the server. This helps ensure that the data
is accurate and complete and that the application can process it correctly.
 Improving user experience: When users enter invalid data, they may receive
error messages or other feedback that helps them correct their mistakes. This
can help prevent frustration and improve the overall user experience.
 Enhancing security: Validation controls can help prevent malicious code or
other attacks that could harm the web application or its users. For example,
validation controls can check for potentially dangerous input such as SQL
injection or cross-site scripting (XSS) attacks.
 Meeting business requirements: Many businesses have specific rules and
requirements for data entry, such as a minimum or a maximum number of
characters or certain formatting conventions. Validation controls can help
ensure that these requirements are met.

Using Stored Procedures With ASP.NET


Stored procedures (sprocs) in SQL Server are generally an ordered series of
Transact-SQL statements bundled into a single logical unit. They allow for variables
and parameters, as well as selection and looping constructs. A key point is that
sprocs are stored in the database rather than in a separate file.

Advantages of stored procedures over inline SQL queries include,

1. Referred to using short names rather than a long string of text; therefore, less
network traffic is required to run the code within the sproc.
2. Pre-optimized and precompiled, so they save an incremental amount of time
with each sproc call/execution.
3. Encapsulate a process for added security or to simply hide the complexity of the
database.
4. Can be called from other sprocs, making them reusable and reducing code size.
5. Stored procedures are executed on the database server and can be better for
performance.
6. Stored procedures are also secure and do not expose database details in
application.
Parameterization

A stored procedure gives us some procedural capability, and also gives us a


performance boost by using mainly two types of parameters,

 Input parameters
 Output parameters

From outside the sproc, parameters can be passed in either by position or reference.

Declaring Parameters in SQL Server Stored Procedures


To declare parameters in a SQL Server stored procedure, you will need,

 The name
 The datatype
 The default value
 The direction

The syntax is,

@parameter_name [AS] datatype [= default|NULL] [VARYING] [ OUTPUT |


OUT]

SQL
Copy

Let's now create a stored procedure named "Submitrecord".

First open Microsoft SQL Server -> Enterprise Manager, then navigate to the
database in which you want to create the stored procedure and select New Stored
Procedure.
 
See the below Stored Procedure Properties for what to enter, then click OK.
 

Now create an application named Store Procedure in .net to use the above sprocs.
Web User Controls in ASP.Net
Web user controls are derived from System.Web.UI.UserControl namespace. These
controls once created, can be added to the aspx page either at design time or
programmatically during run time. But they lack the design time support of setting the
properties created along with the control. They cannot run on their own and they
need to stand on another platform like an aspx page. Even if we try to load it on a
web browser, IIS will not serve the files of the type .ascx.
1. Create a new ASP .Net web application using Visual Studio.Net.
1. Add a Web User Control to the project. Name it as WebUserControl1.ascx.
 
2.
Add a Panel Control on the user control form
3.
1. Add a hyperlink,a TextBox and a button Add a property to the User Control as
follows.
ASP.NET - Custom Controls
ASP.NET allows the users to create controls. These user defined controls are
categorized into:

 User controls
 Custom controls
User Controls
User controls behaves like miniature ASP.NET pages or web forms, which could be
used by many other pages. These are derived from the System.Web.UI.UserControl
class. These controls have the following characteristics:

 They have an .ascx extension.


 They may not contain any <html>, <body>, or <form> tags.
 They have a Control directive instead of a Page directive.

Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a
Dynamic Link Library (DLL) and used as any other ASP.NET server control. They
could be created in either of the following way:

 By deriving a custom control from an existing control


 By composing a new custom control combing two or more existing controls.
 By deriving from the base control class.
ASP.NET - Error Handling
Error handling in ASP.NET has three aspects:


Tracing - tracing the program execution at page level or application level.


Error handling - handling standard errors or custom errors at page level or
application level.


Debugging - stepping through the program, setting break points to analyze
the code

Where there are codes, the chances for exceptions / error always exist so it is very
important for developers when developing web applications to understand the errors
and implement the error handling techniques to avoid breaking pages or providinig
unhandled errors to end uses.

What Exceptions are


an exception is an error condition or unexpected behavior encountered by an
executing program. Exceptions can be raised because of a fault in your code or in
code that you call (such as a shared library), unavailable operating system resources
or unexpected conditions the Common Language Runtime encounters (such as code
that cannot be verified).

Exceptions are nothing but unseen error occurs when executing code logic.
Demo Web Application

I have created a web application as an example to understand the exception


handling.

Sample Code
1. namespace ErrorHandlingDemo  
2. {  
3.     public partial class _Default : Page  
4.     {  
5.         protected void Page_Load(object sender, EventArgs e)  
6.         {  
7.             if (!IsPostBack)  
8.             {  
9.                 string connectionString = ConfigurationManager.Conne
ctionStrings["MyConn"].ConnectionString;  
10.                 string selectSQL = "SELECT * FROM tblEmployees";  
11.                 SqlConnection con = new SqlConnection(connectionStri
ng);  
12.                 SqlCommand cmd = new SqlCommand(selectSQL, con);  
13.                 SqlDataAdapter adapter = new SqlDataAdapter(cmd);  
14.                 DataSet ds = new DataSet();  
15.                 adapter.Fill(ds, "Employees");  
16.                 GridView1.DataSource = ds;  
17.                 GridView1.DataBind();  
18.             }  
19.         }   
20.     }  
21. }  
Using this web page I am trying to display employee's details in a grid view control
on page load. The following is the output page with employee details. 

Example to show data on the webpage from the database using some ADO.NET
code:

Now from this basic what if the table containing employees is deleted or renamed or
the developer has used the wrong table name in the code behind.

I have now changed the table name in the code and complied and run the page.

1. string selectSQL = "SELECT * FROM tblEmployees1";  
After running the application a broken Yellow screen is shown with the message
Invalid Object name. 

But exposing this error message in Yellow page format is a bad practice because:
 It does not make any sense to the end user although it can be helpful for
developers for debugging and investigating the issue.
 
 This exposure can help hackers to get information about your application that is
not good according to security.

Handling Exceptions

Using Try catch finally Block


Using a try catch finally block, exceptions can be handled.

Whenever an exception happens when executing the logic in a try block, the control
is immediately moved to the catch block that reads the exception message and after
catching the exception in the catch block a user-friendly error can be shown to the
end users.
Sample Code
1. namespace ErrorHandlingDemo  
2. {  
3.     public partial class _Default : Page  
4.     {  
5.         protected void Page_Load(object sender, EventArgs e)  
6.         {  
7.             if (!IsPostBack)  
8.             {  
9.                 try  
10.                 {  
11.                     string connectionString = ConfigurationManager.C
onnectionStrings["MyConn"].ConnectionString;  
12.                     string selectSQL = "SELECT * FROM tblEmployees1"
;  
13.                     SqlConnection con = new SqlConnection(connection
String);  
14.                     SqlCommand cmd = new SqlCommand(selectSQL, con); 
 
15.                     SqlDataAdapter adapter = new SqlDataAdapter(cmd)
;  
16.                     DataSet ds = new DataSet();  
17.                     adapter.Fill(ds, "Employees");                  
18.                     GridView1.DataSource = ds;  
19.                     GridView1.DataBind();  
20.                 }  
21.                 catch (Exception ex)  
22.                 {  
23.                     // Log the exception                      
24.                     Label1.Text = "Something Bad happened, Please co
ntact Administrator!!!!";  
25.                 }  
26.                 finally  
27.                 {  
28.                 }  
29.             }  
30.         }  
31.     }  
32. }  
Cookies and Their Types
What is a Cookie?
Cookies are nothing but a small file containing text which is being made when you
enter a website. According to the law, if a website plans on collecting cookies, it
must get consent before doing so. When a new web page is opened, they're
typically written.
Cookies are tiny text files with a name, value, and attribute that are often encrypted.
A web server's name is used to identify cookies. Value is a random alphanumeric
character that holds information such as a unique identifier for the user and other
data. The data can be obtained and utilized to customize the web page once the
code has read the cookie on the server or client computer.

Types of Cookies
Cookies are divided based on their attributes, such as source, duration, and
purpose.
Cookies Based on Source


First-party cookies − The user's browser sets first-party cookies when they visit a
website. The information gathered by first-party cookies is used to calculate page
views, sessions, and the number of users. Ad agencies and advertisers primarily
utilize it to locate potential ad targets.


Third-party cookies − These are set by domains that the user does not visit directly.
This occurs when publishers include third-party elements on their website (such as a
chatbot, social plugins, or advertisements).

Cookies Based on Duration


Session cookie − A session cookie is a file that a website server delivers to a
browser with an identification (a string of letters and numbers) for temporary use
during a set period. By default, session cookies are enabled. Their goal is to make
individual webpages load faster and improve website navigation.


Persistent cookies − Persistent cookies are those that remain in the browser for an
extended length of time. They will only be erased when the cookies expire or the
users clear them from the browser after being installed.

You might also like