cs6001 C# Unit 3

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 103

1

_______________________________________________________________________
UNIT III

APPLICATION DEVELOPMENT ON .NET

Building windows application, Creating


inheriting window forms, SDI and MDI
ADO.NET, DataSet, typed dataset, Data
ADO.NET, handling exceptions, validating

our own window forms with events and controls, menu creation,
application, Dialog Box(Modal and Modeless), accessing data with
Adapter, updating database using stored procedures, SQL Server with
controls, windows application configuration.

_______________________________________________________________________

.NET Framework
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily

on Microsoft

Windows.

It

includes

large class

library known

as Framework

Class Library (FCL) and provides language interoperability(each language can use code written in
other languages) across several programming languages. Programs written for .NET Framework
execute in a software environment (as contrasted to hardware environment), known as Common
Language Runtime (CLR),

an application

virtual machine that provides

services such as

security, memory management, and exception handling. FCL and CLR together constitute .NET
Framework.
FCL

provides user

interface, data

access, database

connectivity, cryptography, web

application development, numericalgorithms, and network communications. Programmers produce


software by combining their own source code with .NET Framework and other libraries.
.NET Framework is intended to be used by most new applications created for the Windows platform.
Microsoft also produces an integrated development environment largely for .NET software
called Visual Studio.
.NET Framework started out as a proprietary framework, although the company worked
to standardize the software stack almost immediately, even before its first release. Despite the
standardization

efforts,

developersparticularly

those

in

the free

and

open-source

software communitiesexpressed their uneasiness with the selected terms and the prospects of
any free and open-source implementation, especially with regard to software patents. Since
then, Microsoft has changed .NET development to more closely follow a contemporary model of a
community-developed software project, including issuing an update to its patent that promises to
address the concerns.
.NET Framework family also includes two versions for mobile or embedded device use. A reduced
version of the framework,.NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smartphones. Additionally, .NET Micro Framework is
targeted at severely resource-constrained devices.

Creating Your First C#


Windows Application
Introduction
C# appears to be the new language of choice around the development community, or
at least the most talked about new language. Microsoft has introduced a language that
will (hopefully) bring together both Visual Basic developers and Visual C++ developers
alike. It is important to remember that, this application is only to show you some of the
most basic components in C#. Here we will design a form that will allow a user to
populate a listbox with customer names they type above.
This article is based on the ideas that Dr.Asad Altimeemy posed in the article he wrote
titled: A Beginners Guide To Dialog Based Applications written in Visual C++. This
article covers essentially the same methods only converted to run in .NET and written
in C#. This code is unfortunately based on Visual Studio .NET Beta 2; please make any
comments regarding the changes to the final release version.

Creating A New Project


To create a new project you need to first load Visual Studio .NET and select under
the Visual C# Projects, Windows Application as in Figure 1. Type the name of the
project below along with selecting the desired location to store your files.

Figure 1. Creating a C# Project.

Designing The Interface


You will need to add the following items onto your form.
Item
GroupBox

Quantit
y
1

Label

ComboBox

Textbox

Button

ListBox

Arrange your items onto the form so that they look something like this. I would suggest
that you place the GroupBox on the form first, otherwise you will need to re-drag all

4
item inside the box once they are on the form. Arrange the items as you see below in
Figure 2.

Figure 2 Design Layouts For Application.

Labels, Labels, Labels..


You will want to add the value Title to the Text property of label1. The Text property
for label2 should be set to First Name and the Text property of label3 should
be.Last Name, big surprise huh? Text properties of button1 should be OK,
button2 should be Clear List and button3 will be
Close. I have set the Text Property of groupBox1 to Customers and Form1 to
Customers as well.
You may also wish to set the Text value of the listBox and comboBox to blank also.

Adding The Code


To begin, when this form loads we need to populate the ComboBox with the appropriate
values. Add the following code by clicking on the form on the outside of the groupBox.
You should see something like this:
Hide Copy Code

private void Form1_Load(object sender, System.EventArgs e)


{
//Add the following code
//to fill the comboBox when
//form loads.
comboBox1.Items.Add("Dr.");
comboBox1.Items.Add("Mr.");

comboBox1.Items.Add("Mrs.");
comboBox1.Items.Add("Ms.");
comboBox1.Focus();
}

We now need to handle what happens when the user hits the OK button after
populating the text boxes. To do this simply click on the Form1.cs[Design]* tab at the
top left to switch from code-view to the form object designer. Double-click on the OK
button and add the following code:
Hide Copy Code

private void button1_Click(object sender, System.EventArgs e)


{
listBox1.Items.Add(comboBox1.Text + " " +
textBox1.Text + " " + textBox2.Text);
textBox1.Text = "";
textBox2.Text = "";
comboBox1.Text = "";
comboBox1.Focus();
}

When we want to allow the user to clear all fields entered into the listBox, we will need
to go back like we did above to the visual designer and double-click on the Clear List
button, this should again switch to a code view and allow you to add the following
code:

Hide Copy Code

private void button2_Click(object sender, System.EventArgs e)


{
listBox1.Items.Clear();
comboBox1.Focus();
}

And finally we want to allow the user to be able to close the application when they want.
To show you another way to allow the user to close the program aside from that catchy
X in the upper right- hand corner, I have provided a button entitledClose. I know,
you were looking for some complex name, werent you? Anyway, before I get off on a
tangent, double-click the Close button and add the following code below:
Hide Copy Code

private void button3_Click(object sender, System.EventArgs e)


{
this.Dispose();
}

Conclusion
Again this small sample application was made to show you how some of the basic
components of a Windows application are controlled in C#. Hopefully, you have a
better understanding of how the new C# language works within a Windows
application. Here is a view of what you might see when running the application.

Figure 3 Final Visual C# Application.

Creating our own window application

Simple Windows Forms Applications


At a minimum, a Windows Forms application consists of the following elements:
One or more classes that derive from System.Windows.Forms.Form.
A Main method that invokes the static (shared in Visual Basic) Run method
and passes
a Form instance to it. The Run method processes messages from the
operating system to the application.
The following code example shows the essential elements of a Windows Forms
application

C#
using System;
using System.Windows.Forms;

public class MyForm : Form {

public MyForm() {
this.Text = "Hello World";
}
[STAThread]
public static void Main(string[] args) {
MyForm aform = new MyForm();
// The Application.Run method processes messages from the operating system
// to your application. If you comment out the next line of code,
// your application will compile and execute, but because it is not in the //
message loop, it will exit after an instance of the form is created.
Application.Run(aform);
}
}

Using Controls in a Windows


Forms
Application
The following code example shows a simple application
that illustrates how Windows Forms applications use
controls and handle events. The example consists of
three buttons on a form; each button changes the
background color when clicked.
C#
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Resources;
using System.Drawing;

public class MyForm : Form {


private Button red;
private Button blue;
private Button green;

public MyForm() : base() {


InitializeComponent();
}

protected override void Dispose(bool disposing) {


base.Dispose(disposing);

9
}

// InitializeComponent is a helper method for the constructor.


// It is included for consistency with code that is
// auto-generated by the Windows Forms designer in Visual Studio.
private void InitializeComponent() {

// A delegate for the click event of a button. The argument to


// the constructor contains a reference to the method that performs the
// event handling logic.
EventHandler handler = new EventHandler(button_Click);

// Creates three buttons, sets their properties, and attaches


// an event handler to each button.

red = new Button();


red.Text = "Red";
red.Location = new Point(100, 50);
red.Size = new Size(50, 50);
red.Click +=handler;
Controls.Add(red);

blue = new Button();


blue.Text = "Blue";
blue.Location = new Point(100, 100);
blue.Size = new Size(50, 50);
blue.Click += handler;
Controls.Add(blue);

10
green = new Button();
green.Text = "Green";
green.Location = new Point(100, 150);

green.Size = new Size(50, 50);


green.Click += handler;
Controls.Add(green);
}

// Event handler.
private void button_Click(object sender, EventArgs e) {
if (sender == red) this.BackColor = Color.Red ;
else if (sender == blue) this.BackColor = Color.Blue;
else this.BackColor = Color.Green;
}
// The STAThreadAttribute informs the common language runtime that
// Windows Forms uses the single-threaded apartment model.
[STAThread]
public static void Main(string[] args) {
Application.Run(new MyForm());
}

10

11

Menu Creation
Defining a Property in
Windows
Forms Controls
One common aspect of Web sites of any complexity is a
navigational menu. You can use the Menu control in
ASP.NET to easily set up a complex navigational menu
without writing code. The Menu control allows for
multiple display options, including a static display where
the menu is fully exposed and a dynamic display where
portions of the menu appear as the mouse pointer
moves over the parent menu item. The control also
provides a combination of static and dynamic display
modes that allow a series of root items that are static,
but with child menu items that appear dynamically.
You can configure the ASP.NET Menu control in the
designer with
static links to your pages or you can bind it
automatically to a hierarchical data source such as an
XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
Creating a basic menu and configuring it statically
to link to your pages.
Creating a more complex menu that is bound to a
11

12

12

Web.sitemap XML
file.
Adjusting the orientation of a menu.

13

Configuring multiple levels of static display versus


dynamic
display.

Walkthrough: Displaying a
Menu on Web Pages
.NET Framework 4
Other Versions

This walkthrough illustrates how to place and configure an ASP.NET Menu


control on a Web page.
One common aspect of Web sites of any complexity is a navigational menu. You can
use
the Menu control in ASP.NET to easily set up a complex navigational menu without
writing code. The Menu control allows for multiple display options, including a static
display where the menu
is fully exposed and a dynamic display where portions of the menu appear as the
mouse pointer moves over the parent menu item. The control also provides a
combination of static and dynamic display modes that allow a series of root items
that are static, but with child menu
items that appear dynamically.
You can configure the ASP.NET Menu control in the designer with static links to
your pages or you can bind it automatically to a hierarchical data source such as
an XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
Creating a basic menu and configuring it statically to link to your pages.
Creating a more complex menu that is bound to a Web.sitemap XML file.
Adjusting the orientation of a menu.
Configuring multiple levels of static display versus dynamic display.

Prerequisites
In order to complete this walkthrough, you will need:
Visual Studio or Visual Web Developer Express installed on your computer.

13

Note

14

If you are using Visual Studio, the walkthrough assumes that you selected the Web
Development collection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.

Creating the Web Site


For this walkthrough, you will create an empty Web site project and add a page to it.
This walkthrough uses a Web site project. You could use a Web application project
instead. For information about the difference between these Web project types,
see Web Application Projects versus Web Site Projects.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then
select ASP.NET Empty Web Site.
4. In the Web location box, select File System, and then enter the name of
the folder
where you want to keep the pages for your
Web site. For example, type the folder name
C:\WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes a Web.config file.
6. In Solution Explorer, right-click the root of your Web site, and then click
Add New
Item.
7. Select Web Form, name the file Default.aspx, and then click Add.

Creating a Basic Menu


Although the master page within the ASP.NET Web site
template includes a menu, you can add an additional
menu specifically for the Default.aspx page for the
purpose of this walkthrough. The first step in creating a
menu for your page is the placement of
a Menu control.

To add a Menu control to the page


1. Switch to or open Default.aspx, and then
switch to Design view.
2. From the Navigation control group in the
14

15

Toolbox, drag a Menu control onto the page.

15

16

For this example, you will orient the menu horizontally


rather than
vertically.

To position the Menu control horizontally

Right-click the Menu control, click Properties,


and then set Orientation to Horizontal.

onfiguring a Basic Menu

In this section, you will define the menu items by using the Menu
Item Editor. To edit Menu control items
1. Right-click the Menu control, and then click Edit Menu Items.
The Menu Item Editor
appears.
2. Under Items, click the Add a root item icon.
3. Under Properties for the new item,
set Text to Home and NavigateURL to Default.aspx.
4. Under Items, click the Add a root item icon.
5. Under Properties, set Text to Products and NavigateURL to
Products.aspx.
6. Under Items, click the Add a root item icon.
7. Under Properties, set Text to Services and NavigateURL to
Services.aspx.
8. Click OK.
If you look at the source for Default.aspx, you will see that the menu items and
links are stated declaratively in the control.

To create the target pages

1. In Solution Explorer, right-click the root of your


Web site, and then click Add New Item.
2. Click Web Form, name the file Products.aspx, and
then
click Add.
3. Repeat the preceding steps and
create a file named Services.aspx.
16

17

Testing the Menu


With your pages and menu in place, you can try it out.

To test the Menu control


1. Click Default.aspx in Solution Explorer and then press
CTRL+F5 to run the Default.aspx
page.
2. Move the pointer over the items; the browser's
status bar at the bottom of the page (if visible) will
show what page is linked.
3. Click a link to jump to the page.

Creating a Menu Bound to a Site


Map
In the last section, you created a simple static menu
configured declaratively within the page. In this
section, you skip editing
the Menu control items directly, and instead bind the
control to a
Web.sitemap file as an XML data source. This allows
the Menu control's structure to be maintained within a
separate XML file that can be easily updated without
modifying the page or using the designer.
For this example you will use a second Menu control.

To create a second Menu control


From the Navigation group of the Toolbox,
drag a second Menu control onto the
Default.aspx page.
Next, you will need a Web.sitemap file to bind to.

To create a site map file


17

18

1. In Solution Explorer, right-click the root of your


Web site, and then click Add New Item.
2. In the Add New Item dialog box, click Site Map.
3. Click Add.
4. Place the following XML code in the Web.sitemap file.
The XML represents the structure of the menu. Nested
nodes
become child menu items of parent node menu items.
<siteMap>
<siteMapNode title="Home" description="Home"
url="default.aspx" >
<siteMapNode title="Products"
description="Our products"
url="Products.aspx">
<siteMapNode title="Hardware"
description="Hardware choices"
url="Hardware.aspx" />
<siteMapNode title="Software"
description="Software choices"
url="Software.aspx" />
</siteMapNode>
<siteMapNode title="Services"
description="Services we offer"
url="Services.aspx">
<siteMapNode title="Training"
description="Training classes"
url="Training.aspx" />
<siteMapNode title="Consulting"
description="Consulting services"
18

19

url="Consulting.aspx" />
<siteMapNode title="Support"
description="Support plans"
url="Support.aspx" />
</siteMapNode>
</siteMapNode>
</siteMap>
5.Save the file.

Binding to a Site Map


Now you can create a navigation data source that points
to your
Web.sitemap file and bind your Menu control to it.

To bind to a Menu control to a site map


1. Open the Default.aspx file, and then switch to Design
view.
2. Click the smart tag of the new Menu control to
display the Menu Tasks dialog box.
3. In the Menu Tasks dialog box, in the Choose Data
Source drop-down list, click New Data Source.
The Data Source Configuration Wizard dialog box
appears.
4. Click Site Map.
Under Specify an ID for the data source,
the default name, SiteMapDataSource1,
appears.
5. Click OK.

Testing Site Map Binding


19

20

With your pages and menu in place, you can try it out.

To test the site map binding


1. Press CTRL+F5 to run the Default.aspx page.
2. Move the pointer over the Home menu item of the
second, vertical menu.
Products and Services appear.
3. Move the pointer over Products.
Hardware and Software appear.
If you look at the source code for Default.aspx, you
will
notice that unlike the first menu item, the items are
not specified declaratively; instead, the data source
is referenced by the Menu control.
4. Close the Browser window.

How to: Inherit Windows


Forms
Creating new Windows Forms by inheriting from base
forms is a handy way to duplicate your best efforts
without going through the process of entirely recreating
a form every time you require it. For more information
about inheriting forms at design time using the
Inheritance Picker dialog box and how to visually
distinguish between security levels of inherited controls,
see How to: Inherit Forms Using the Inheritance Picker
Dialog Box.
Note In order to inherit from a form, the file or
20

21

namespace
containing that form must have been built into an
executable file or DLL. To build the project, choose Build
from the Build menu. Also, a reference to the namespace
must be added to the class inheriting the form. The
dialog boxes and menu commands you see might differ
from those described in Help depending on your active
settings or edition. To change your settings, choose
Import and Export Settings on the Tools menu. For
more information, see Customizing Development Settings
in Visual Studio.

To inherit a form
programmatically
1. In your class, add a reference to the namespace
containing the form you wish to inherit from.
2. In the class definition, add a reference to the form to
inherit
from. The reference should include the namespace
that contains the form, followed by a period, then
the name of the base form itself.
C#
public class Form2 : Namespace1.Form1

21

22

SDI and MDI


Single document interface
SDI applications allow only one open document frame window at a time. It's made up of one
or more independent windows, which appears separately on the windows desktop. An
example of this would be a simple text document(Notepad).
MDI applications allow multiple document frame windows to be open in the same instance
of an application. An MDI application has a window within which multiple MDI child
windows, which are frame windows themselves, can be opened, each containing a separate
document. In some applications, the child windows can be of different types, such as chart
windows and spreadsheet windows. In that case, the menu bar can change as MDI child
windows of different types are activated.

Multiple document interface


A multiple document interface (MDI) is a graphical user interface in which multiple
windows reside under a single parent window. Such systems often allow child windows to
embed other windows inside them as well, creating complex nested hierarchies. This
contrasts withsingle document interfaces (SDI) where all windows are independent of each
other.

22

23

Comparison with single document interface


In the usability community, there has been much debate about whether the multiple
document or single document interface is preferable. Software companies have used both
interfaces with mixed responses. For example, Microsoft changed its Office applications
from SDI to MDI mode and then back to SDI, although the degree of implementation varies
from one component to another. SDI can be more useful in cases where users switch more
often between separate applications than among the windows of one application.
The disadvantage of MDI usually cited is its lack of information about the currently opened
windows: In MDI applications, the application developer must provide a way to switch
between documents or view a list of open windows, and the user might have to use an
application-specific menu ("window list" or something similar) to switch between open
documents. This is in contrast to SDI applications, where the window manager's task
bar or task manager displays the currently opened windows. However, in recent years it
has become increasingly common for MDI applications to use "tabs" to display the currently
opened windows, which has made this criticism somewhat obsolete. An interface in which
tabs are used to manage open documents is referred to as a "tabbed document interface"
(TDI).
Another option is "tiled" panes or windows, which make it easier to prevent content
from overlapping.
Some applications allow the user to switch between these modes at their choosing,
depending on personal preference or the task at hand.
Nearly all graphical user interface toolkits to date provide at least one solution for
designing MDIs, with an exception being Apple's Cocoa API. The Java GUI toolkit, Swing,
for instance, provides the class javax.swing.JDesktopPane which serves as a container
for individual frames (class javax.swing.JInternalFrame ). GTK+ lacks any
standardized
support for MDI.

Advantages[edit]

With multiple document interfaces (and also tabbed document interfaces), a single
menu bar and/or toolbar is shared between all child windows, reducing clutter and
23

24

increasing efficient use of screen space. This argument is less relevant on an operating
system which uses a common menu bar.

An application's child windows can be hidden/shown/minimized/maximized as a whole.

Features such as "Tile" and "Cascade" can be implemented for the child windows.

Authors of cross-platform applications can provide their users with consistent application
behaviour between platforms.

If the windowing environment and OS lack good window management, the application
author can implement it themselves.

Modularity: An advanced window manager can be upgraded independently of the


applications

Disadvantages[edit]

Can be tricky to implement on desktops using multiple monitors as the parent window
may need to span two or more monitors, hiding sections.

Virtual desktops cannot be spanned by children of the MDI. However, in some cases,
this is solveable by initiating another parent window; this is the case
in Opera andChrome, for example, which allows tabs/child windows to be dragged
outside of the parent window to start their own parent window. In other cases, each child
window is also a parent window, forming a new, "virtual" MDI [1].

MDI can make it more difficult to work with several applications at once, by restricting
the ways in which windows from multiple applications can be arranged together without
obscuring each other.

The shared menu might change, which may cause confusion to some users.

MDI child windows behave differently from those in single document


interface applications, requiring users to learn two subtly different windowing concepts.
Similarly, the MDI parent window behaves like the desktop in many respects, but has
enough differences to confuse some users.

Deeply nested, branching hierarchies of child windows can be confusing.

Many window managers have built-in support for manipulating groups of separate
windows, which is typically more flexible than MDI in that windows can be grouped and
ungrouped arbitrarily. A typical policy is to group automatically windows that belong to
the same application. This arguably makes MDI redundant by providing a solution to the
24

25

same problem.

25

26

Controls and hotkeys learned for the MDI application may not apply to others, whereas
with an advanced Window Manager, more behavior and user preference settings are
shared across client applications on the same system

Without an MDI frame window, floating toolbars from one application can clutter the
workspace of other applications, potentially confusing users with the jumble of
interfaces.

SDI and MDI


MFC makes it easy to work with both single-document interface (SDI) and
multiple-document interface (MDI) applications.
SDI applications allow only one open document frame window at a time. MDI
applications allow multiple document frame windows to be open in the same
instance of an application. An MDI application has a window within which multiple
MDI child windows, which are frame windows themselves, can be opened, each
containing a separate document. In some applications, the child windows can be of
different types, such as chart windows and spreadsheet windows. In
that case, the menu bar can change as MDI child windows of different types are
activated.

Dialog box modal and


modeless
A modal from is one that has to be dealt with before a user can continue. An example
is the Change Case dialogue box in Microsoft Word. If you try to click away from the
dialogue box, you'll here a beep to indicate an error. Until you click either the Cancel or
OK buttons, the programme won't let you click anywhere else.
The second form you've just created is called a Modeless form. These are forms
than can be hidden or sent to the taskbar. You can then return to the main form or
programme and do things with it.
A Modal form is sometimes called a dialogue box. And we'll see how to create one
of these now.
Add a second button to your Form1. Change the Name property of the new
26

27

button tobtnDialogueBox. Double click the new button and add the following
code:
Dim frmDialogue As New frmSecond
frmDialogue.ShowDialog()
To display a form as a Modal dialogue box, you use the ShowDialog method. If
you use the Show method, the form is displayed as a Modeless form.
Run your programme. Click your new button, and the second form should display.
Move it out the way and try to click a button on Form1. You won't be able to. The
second form has to be dealt with before you can access Form1.
When the form is a Modal dialogue box, you can create OK and Cancel buttons for
it. VB.NET then has a trick up its sleeve for these types of buttons. We'll see that
trick now.

OK and Cancel Buttons

In the design environment, Click the Tab for your frmSecond. When the form is
displayed in the design window, add two buttons to it (Make sure you're adding the
buttons to the second form and NOT Form1). Change the Name property of the
first
button to btnOK, and the Name property of the second to btnCancel. Double click your
OK button and add the following code to it:
Me.DialogResult = DialogResult.OK
The Me keyword refers to the current form. When you type a full stop,
select DialogResult from the pop up list that appears. DialogResult is a property of
the Form. It can accept a range of values. As soon as you type a space after the
equals sign, you'll see a list with these values on it (VB NET 2008 only. In VB 2010,
you have to type the DialogResult):

27

28

As you can see, one of these values is DialogResult.OK. This indicates that you want
to use this button as an OK button. When the button is clicked, VB.NET will return a
result of OK for this button.
Access the code for your Cancel button and add the following line:
Me.DialogResult = DialogResult.Cancel
For the Cancel button, we're just selecting DialogResult.Cancel from the list. When
the button is clicked, VB.NET will return a result of Cancel for this button.
You can test to see what value is stored in Me.DialogResult. But you do that from
the button that displays the form, Form1 for us.
So access your Form1 code, and locate the lines that display the second form. The
two lines should be these:
Dim frmDialogue As New frmSecond
frmDialogue.ShowDialog()
Change the second line to this:
If frmDialogue.ShowDialog() = DialogResult.OK Then
MessageBox.Show("OK Button Clicked")
End If
To get at the value of the button clicked, you test to see what result
the ShowDialog property is. If theShowDialog property of frmDialogue is OK then
you can execute the code that needs executing. If the Cancel button was clicked,
however, you don't have to do anything: VB.NET will take of closing your Modal
dialogue box for you!
28

29

Run your programme and test it out. Click your button to bring up your Modal dialogue
box. Click the OK button, and you should see the message box display. Bring the
Modal dialogue box up a second time and then click the Cancel button. The form will
just close down.

29

30

Modal Dialog Boxe


There are two types of
dialog boxes: modal and
modeless.
A Modal dialog box is one that the user must first close in order to have access to any other
framed window or dialog box of the same application. One of the scenarios in which you use
a dialog box is to create an application that is centered around one. In this case, if either
there is no other form or dialog box in your application or all the other forms or dialog boxes
depend on this central dialog box, it must be created as modal. Such an application is
referred to as dialog-based.
Some applications require various dialog boxes to complete their functionality. When in
case, you may need to call one dialog box from another and display it as modal. Here is
an example:
The Date and Time dialog box of WordPad is modal: when it is displaying, the user cannot use
any other part of WordPad unless he or she closes th

is object first
After creating a dialog used as an addition to an existing form or an existing dialog box, to
call it as modal, use the ShowDialog() method.

Modeless Dialog Boxes


A dialog box is referred to as modeless if the user does not have to close it in order to
continue using the application that owns the dialog box. A modeless dialog box has the
following characteristics

30

It has a thin border

31

It can be neither minimized nor maximized. This means that it is not equipped with
the Minimize or the Maximize buttons

It is not represented on the taskbar with a button

It must provide a way for the user to close it

Here is an example:
The Find (and the Replace) dialog box of WordPad (also the Find and the Replace
dialog boxes of most applications) is an example of a modeless dialog box. If it is
opened, the user does not have to close it in order to use the application or the
document in the background.

Since the modeless dialog box does not display its button on the task bar, the user
should know that the dialog box is opened. To make the presence of a modeless dialog
box obvious to the user, it typically displays on top of its host application until the user
closes it.
A modeless dialog box is created from a form but it should look like a regular dialog box
or
a
tool
window.
Therefore,
to
create
a
modeless
dialog
box,
set
the FormBorderStyle property
to
an
appropriate
value
such
as FixedSingle, FixedToolWindow, Sizable or SizableToolWindow.
Also,
set
its ShowInTaskbar property to False.
After creating the dialog box, to display it as modeless, call the Show() method. The
fundamental difference between the ShowDialog() and the Show() methods is that the
former displays a modal dialog box, which makes sure that the called dialog box cannot

31

32
go in the background of the main application. By contrast, the Show() method only calls
the dialog box every time it is requested. For this reason, it is up to you to make sure that
the modeless dialog box always remains on top of the application. This is easily taken care
of by setting the BooleanTopMost property of the form to True.
There are two main ways a normal modeless dialog box can be dismissed:
If the user has finished using it, he or she can close it and recall it at will

When the form or application that owns the modeless dialog box is closed, the form
or application closes the modeless dialog if it is opened; this means that you don't
need to find out whether a modeless dialog box is still opened when the application
is being destroyed: either the user or the application itself will take care of closing it

An Application With Various Forms or Dialog boxes


When you
create a
Windows Forms Application, the
starting form is made available to you. If one form is not
enough for your application, you can add as many as
necessary. To add (or to create) a (new) form, you have
various options:
On the main menu, you can click Project -> Add New
Item...
On the main menu, you can click File -> Add New Item...

In Solution Explorer, you can right-click the name of the


project, position the mouse on Add, and click Add New
Item...

In the Add New Item dialog box and in the Templates


section, click Window Form (.NET), provide a name in the
Name edit box then click Open.
If your application is using various forms and you want to
display a particular one at design time:

In the Forms Designer, you can click the tab that


corresponds to the desired form and that has [Design]

On the main menu, you can click Window and click the
name of the form in the list under Close All Documents

In Solution Explorer, expand the Header Files node if


necessary and double-click the name of the desired form
that has the .h extension

If you visually add two (or more) forms to your application, you
may need to link them, allow one to call the other. To do this,
in the top section of the file, type #include followed by the
name of the header file in which the form was defined. In the
section where you want to access the form, declare a handle to
the class of the form and use the new operator to allocate
memory for it. To display the other form, you can call
its Show() method.

Practical Learning: Using Various Forms


1. Display the first form

32

33
2. Double-click the New Property... button and implement the event as follows:
private void btnNewProperty_Click(object sender, EventArgs e)
{
Random rnd = new Random();

33

34

PropertyEditor dlgEditor = new PropertyEditor();


if (dlgEditor.ShowDialog() == DialogResult.OK)
{
ListViewItem lvi = lvwProperties.Items.Add(
rnd.Next(100000, 999999).ToString());
lvi.SubItems.Add(dlgEditor.txtPropertyType.Text);
lvi.SubItems.Add(dlgEditor.txtBedrooms.Text);
lvi.SubItems.Add(dlgEditor.txtBathrooms.Text);
lvi.SubItems.Add(dlgEditor.txtMonthlyRent.Text);
}
}

3.

Execute the application and click the New Property... button

4. Create a property

5.

Press Enter

6. Create a few more properties and press Enter each time

34

35

7. Close it and return to your programming environment

35

36

ADO.NET
Introduction
This article aims at understanding the various concepts and classes available for
data access in ADO.NET. This article is meant for absolute beginners and discusses
various techniques of data access using ADO.NET.

Background
ADO.NET is a set of classes that comes with the Microsoft .NET framework to facilitate
data access from managed languages. ADO.NET has been in existence for a long time
and it provides a comprehensive and complete set of libraries for data access. The
strength of ADO.NET is firstly that it lets applications access various types of data using
the same methodology. If I know how to use ADO.NET to access a SQL Server database
then the same methodology can be used to access any other type of database (like
Oracle or MS Access) by just using a different set of classes. Secondly, ADO.NET
provides two models for data access: a connected model where I can keep the
connection with the database and perform data access, and another way is to get all
the data in ADO.NET
objects that let us perform data access on disconnected objects.
Note: Many developers and development houses are now using ORMs to perform
data access instead of using ADO.NET. ORMs provide a lot of data access
functionality out of the box and
relieves users from writing mundane data access code again and again. Still, I think that
knowing and understanding ADO.NET is crucial as a .NET developer as it gives a better
understanding of the data
access methodologies. Also, there are many development houses that are still using
ADO.NET.
Let us try to visualize ADO.NET data access using the following diagram:

36

37

The diagram above shows that ADO.NET can be used with any kind of application, i.e., it
can be used from a Windows Forms application, an ASP.NET application, or from a WPF
and/or Silverlight application. Also, the data store underneath can be any data store,
SQL Server, Access, or Oracle. It is just a matter of using the right set of classes specific
to that data store and the methodology will remain the same.

Using the code


Let us try to understand a few ADO.NET classes and methodologies by writing a small
web application. This application uses a sample database from Microsoft (subset of the
Pubs database) and we will use this database for understanding the various classes
and methods of ADO.NET. We will be using ADO.NET classes specific to SQL Server but
once it is understood, the basic philosophy remains the same and can be applied with
any data store.
Before jumping into the code, we will have to understand some of the important objects
of
ADO.NET. In a typical scenario requiring data access, we need to perform four major
tasks:
1.
2.
3.
4.

Connecting to the database


Passing the request to the database, i.e., a command like select, insert, or update.
Getting back the results, i.e., rows and/or the number of rows effected.
Storing the result and displaying it to the user.
This can be visualized as:

37

38

So now we need to understand how we can achieve these functionalities


using ADO.NET.

The
Connection
The ADO.NET Connection class is used to establish a connection to the database. The
Connection class uses a ConnectionString to identify the database server location,
authentication parameters, and other information to connect to the database. This
ConnectionString is typically stored in
the
web.config.
Hide Copy Code

<connectionStrings>
<add name="MyConnectionString"
connectionString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|
DataDirectory|\PUBS.MDF; Integrated Security=True;User Instance=True"
/>
</connectionStrings>

Let us see how we can use the SqlConnection class to establish a connection with a
database.
Hide Copy Code

private SqlConnection con = null; con = new


SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

Now we have a connection ready with our database. Whenever we want to retrieve

38

39
data, we just need to open the connection, perform the operation, and close the
connection.

39

40

Storing the Result


Before we can jump to understanding how we can execute commands on a database, we
first need
to understand how we can store the results and these results can be displayed to the
user. To get the hang of how we can store the results, we need to understand a few
ADO.NET objects.

DataReader - A DataReader is an object that can be used to access the results


sequentially from a database. The DataReader is used to get forward only sequential
results as the query executes. This is used with the Command object (we will see the
usage shortly).
Dataset - The Dataset can be thought of as an in-memory representation of a database.
A DataSet is a disconnected data access object. The result of the query can be stored
in a Dataset. The DataSet containsDataTables. The DataTables contain DataRow and
DataColumns.
A DataSet or a DataTable can be used with a Command and a DataAdapter
object to store query results.
DataAdapter - A DataAdapter object is used to fill a DataSet/DataTable with query
results. This can be thought of as the adapter between the connected and disconnected
data models. A
Command object will be used to execute the query and a DataAdapter will use this
Command
object and fill the query results coming from the database into a DataSet/DataTable.
Note:

1. There are more objects that can/are used to store results but we will mainly be using
these in this article.
2. The usage and implentation of these objects are in the next section, as understanding
the Command object is required before that.

The Command
Once we have the connection ready, the next step would be to tell the database about
what operation we need to perform on the database. This can be done using the
Command object. We will be using SqlCommand to tell the database about the
operation we need to perform. The typical commands on a database will be:
1.
2.
3.
4.

Select Command - This will return a set of rows to the application.


Insert Command - This will return the number of rows inserted.
Delete Command - This will return the number of rows deleted.
Update Command - This will return the number of rows updated.
Note: We are only talking about data manipulation commands in this article.

40

41

All these commands expect SQL syntax. This SQL can either be passed from the
application or can be written in the form of Stored Procedures and executed using a
SqlCommand.

41

42

Using a Stored Procedure with a Command


If we want to use a Stored Procedure with a Command object then we need to specify it
as:
Hide Copy Code

cmd = con.CreateCommand();
// This will specify that we are passing the stored procedures name
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandName; // This will be the stored procedures name

If the Stored Procedure is expecting some parameters then we can pass these
parameters by creating instances ofSqlParameter objects as:
Hide Copy Code

SqlCommand cmd = con.CreateCommand();


// This will specify that we are passing the stored procedures name
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandName; // This will be the stored procedures
name SqlParameter param = new SqlParameter("@id", txtSearch.Text);
cmd.Parameters.Add(param);

Passing a SQL query from an application using a Command


If we want to pass a SQL query from our application then we can use the SqlCommand
as:
Hide Copy Code

SqlCommand cmd = con.CreateCommand();


cmd.CommandType = CommandType.Text; //This will specify that we are passing query from
application
string query = "select * from Authors";
cmd.CommandText = query;

There is one important thing to understand here and that is SqlParameters. Many a
times we will need to pass parameters in our SQL query. This can be done in two
ways: we can create a query using string concatenation like:
Hide Copy Code

SqlCommand cmd = con.CreateCommand();


//This will specify that we are passing query from application
cmd.CommandType = CommandType.Text;
string query = "select * from Authors where authorId = '" + txtSearch.Text + "'";
cmd.CommandText = query;

42

43

This is not recommended as this approach is error prone and is vulnerable to SQL
Injection attacks.
So whenever we need to pass parameters to a query the preferred way is using
SqlParameters. The
same query can be written as:
Hide Copy Code

SqlCommand cmd = con.CreateCommand();


//This will specify that we are passing query from application
cmd.CommandType = CommandType.Text;
string query = "select * from Authors where authorId = @id";
cmd.CommandText = query;
SqlParameter param = new SqlParameter("@id", txtSearch.Text);
cmd.Parameters.Add(param);

Using SqlParameters gives a cleaner, less error prone and SQL injection safe
(comparative) code.

Executing the Select Command


Now let us see how we can retrieve the result of a Select command in the form of a
DataTable.
Hide Shrink

public DataTable ExecuteSelectCommand(string CommandName, CommandType cmdType)


{
SqlCommand cmd = null;
DataTable table = new DataTable();
cmd = con.CreateCommand();
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
try
{
con.Open();
SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally

43

Copy Code

44
{
cmd.Dispose();
cmd = null;
con.Close();
}

44

return table;
}
public DataTable ExecuteParamerizedSelectCommand(string
CommandName, CommandType cmdType,
SqlParameter[] param)
{
SqlCommand cmd = null;
DataTable table = new DataTable();
cmd = con.CreateCommand();
cmd.CommandType = cmdType;
cmd.CommandText =
CommandName;
cmd.Parameters.AddRange(para
m);
try
{
con.Open();
SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}
return table;
}

Executing Update, Delete, and Insert Commands


Commands like insert, update, delete are executed by calling the ExecuteNonQuery
method
of SqlCommand. Let us see how we can write a simple function that will execute these
commands.
These commands can be used by passing a query from the application or by invoking
Stored
Procedures (same as we saw above).
Hide Shrink

Copy Code

public bool ExecuteNonQuery(string CommandName, CommandType cmdType, SqlParameter[] pars)


{
SqlCommand cmd = null;

int res = 0;
cmd = con.CreateCommand();
cmd.CommandType = cmdType;

cmd.CommandText = CommandName;
cmd.Parameters.AddRange(pars);
try
{
con.Open();
res = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}
if (res >= 1)
{
return true;
}
return false;
}

Using the sample application


The first thing to notice in the application is that it contains a class that is
responsible for all the ADO.NET logic. The class DataAccess (file: DataAccess.cs)
contains all the ADO.NET classes and methods. All the pages use this class. This
class can be reused in any application with some minor application specific changes.
The class diagram for the class is:

The sample application contains four pages:

Authors.aspx
Titles.aspx
AddAuthors.aspx
AddTitles.aspx

The author pages, i.e., Authors.aspx and AddAuthors.aspx, use Stored Procedures to
perform the operations whereas the title pages pass all the queries from the application
to the database. We have mainly implemented Select and Insert commands but Update
and Delete can be implemented on the same lines as Insert.
Some things worth mentioning about the application are:

This should in no way be treated as a design reference for the data access layer.
This is only to demonstrate ADO.NET logic.
The code is written in such a way as to provide a clear understanding from a beginner's
perspective, i.e., experienced programmers will find a lot of possible optimizations in
the code.
No client side or server side validations have been provided as that was not the scope of
this article.
There is no design (architecture wise and look wise) in this application.

DataSet
Keyword Array Dictionary List String Sub ArrayList Cast
Class Console Dates DataTable DateTime Enum File For Form
at If IndexOf Lambda LINQ Nothing Parse Process Property R
egex Replace Select Sort Split StringBuilder Substring
DataSet stores many DataTables in VB.NET programs. A DataSet is
conceptually a set of DataTables and other information about those
tables. It is an abstraction that makes programs simpler to develop.
Info: This is a container for multiple DataTables. You can use it to
create XML. It is a useful abstraction for simplifying programs.
Example. This example shows how to add multiple DataTables to a
DataSet collection. You should have some DataTables instantiated.
Then, create a new DataSet with the constructor. Next, add tables
with the Tables.Add subroutine invocation.
Finally:We demonstrate that the GetXml() function will print
formatted XML that represents the data.

VB.NET program that uses DataSet


Module Module1
Sub Main()
' Two DataTables.
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
table1.Rows.Add("mark", 2)
Dim table2 As DataTable = New
DataTable("medications")
table2.Columns.Add("id")
table2.Columns.Add("medication")
table2.Rows.Add(1, "atenolol")
table2.Rows.Add(2, "amoxicillin")
' Create a DataSet. Put both tables in it.
Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)
' Visualize DataSet.
Console.WriteLine(set1.GetXml())
End Sub
End Module
Output
<office>
<patients>
<name>sam</name>
<id>1</id>
</patients>
<patients>
<name>mark</name>
<id>2</id>
</patients>
<medications>

<id>1</id>
<medication>atenolol</medication>
</medications>
<medications>
<id>2</id>
<medication>amoxicillin</medication>
</medications>
</office>

Using. The Using resource acquisition statement can be used


with the DataSet. This sometimes alleviates memory usage
problems in programs. The following example demonstrates
the correct syntax for the Using statement and a DataSet
instance.
VB.NET program that shows Using statement with DataSet
Module Module1
Sub Main()
Using set1 As DataSet = New DataSet("office")
' Use set1 here.
End Using
End Sub
End Module

Namespace, Prefix. One of the uses of DataSet is that it


allows you to get XML data for its contents. This can
generate complete XML files. With the Namespace and Prefix
properties, you can form correct XML for your specific
application's requirements.
Here:Look at how the
Namespace "y" and the
Prefix "x" appear in the
output of this program.
VB.NET program that uses Namespace and Prefix
Module Module1
Sub Main()
' Create DataTable.

Dim table1 As DataTable = New DataTable("patients")


table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
' Create DataSet.
Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Namespace = "y"
set1.Prefix = "x"
' Visualize it.
Console.WriteLine(set1.GetXml())
End Sub
End Module
Output
<x:office xmlns:x="y">
<patients xmlns="y">
<name>sam</name>
<id>1</id>
</patients>
</x:office>

DataSetName. It is possible to change the name of your


DataSet. When you call the DataSet constructor with a String
argument, that sets the initial name. You can also modify or
read the name by using the DataSetName String property.
VB.NET program that uses DataSetName
Module Module1
Sub Main()
' Initialize DataSet.
Dim set1 As DataSet = New DataSet("office")
' Display, set, then display DataSetName.
Console.WriteLine(set1.DataSetName)
set1.DataSetName = "unknown"
Console.WriteLine(set1.DataSetName)
End Sub

End Module
Output
office
unknown

Copy, Clear. The DataSet provides ways for you to copy the
entire contents of it into another object. You can use the
Copy function for this purpose. We also show the Clear
subroutine here, which scrubs the contents of the enclosed
DataTables.
Tip:When we call Clear,
the copied DataSet is
not changed. The two
objects are in separate
memory.
VB.NET program that uses Copy and Clear
Module Module1
Sub Main()
Dim table1 = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
Dim table2 = New DataTable("medications")
table2.Columns.Add("id")
table2.Columns.Add("medication")
table2.Rows.Add(1, "atenolol")
' Create a DataSet instance.
Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)
' Copy.
Dim copy As DataSet = set1.Copy()

' Clear original DataSet instance.


set1.Clear()
Console.WriteLine("set: {0}", set1.GetXml())
Console.WriteLine("copy: {0}", copy.GetXml())
End Sub
End Module
Output
set: <office />
copy: <office>
<patients>
<name>sam</name>
<id>1</id>
</patients>
<medications>
<id>1</id>
<medication>atenolol</medication>
</medications>
</office>

Loop through DataTables. Sometimes it is useful to loop


through the DataTable instances stored in the enclosing
DataSet. With a For-loop, we loop from 0 to the Count of the
Tables collection minus one. Then we get each collection
from the index value.
VB.NET program that loops through tables
Module Module1
Sub Main()
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
Dim table2 As DataTable = New
DataTable("medications")
table2.Columns.Add("id")
table2.Columns.Add("medication")

table2.Rows.Add(1, "atenolol")
table2.Rows.Add(6, "trifluoperazine")
' Create the DataSet.
Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)
' Loop over tables in the DataSet.
Dim collection As DataTableCollection = set1.Tables
For i As Integer = 0 To collection.Count - 1
' Get table.
Dim table As DataTable = collection(i)
Console.WriteLine("{0}: {1}", i,
table.TableName)
Next
' First table.
Console.WriteLine("x: {0}",
set1.Tables(0).TableName)
' Row count of medications table.
Console.WriteLine("y: {0}",
set1.Tables("medications").Rows.Count)
End Sub
End Module
Output
0:
1:
x:
y:

patients
medications
patients
2

Typed DataSets in .NET


Introduction
As all of we know, we can specify the Data type when we create a
DataColumn for a DataTable. This is to enforce the runtime Type-safety for
the column so that only data of specified data type can be stored in the
column. In the same way, in most of the cases we prefer to make a DataSet
itself as Type-safe so as to protect it from runtime mismatch. Hence Typed
DataSets generate classes that expose each object the in the DataSet in
Type-safe manner. These classes inherits directly from DataSet class.

Let us look into a small example which explain the Typed DataSet,
1. Using DataSet:
//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = "12345";//This will generate runtime error as
empno column is integer

If we observe above code we will get a runtime error when this code gets
executed as the value assigned to the column (empno) does not take string
value. Also any misspell of the column will generate a runtime error. And
also we need to go thro the hierarchy to get the final value.

2. Using Typed DataSet:

//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
EmployeeDS dsEmp = new EmployeeDS ();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());
//Assign a value to the first column
dsEmp.EMPLOYEE[0].empno = "12345";//This will generate compile time error.

If we see above code, a typed dataset is very much similar to a normal


dataset. But the only difference is that the sehema is already present for the
same. Hence any mismatch in the column will generate compile time errors
rather than runtime error as in the case of normal dataset. Also accessing
the column value is much easier than the normal dataset as the column
definition will be available in the schema.
How to Generate Typed DataSet?
A Typed DataSet can be generated in two ways,
1. Using Visual Studio .NET IDE.
2. Using XSD.exe (Using VS.Net command prompt)
Open VS.Net command prompt and Type XSD /? For the help on this exe.

Creating a Typed DataSet using Visual Studio .NET IDE


Let me explain a step by step procedure to create a Typed DataSet,
1. Open VS .Net IDE and Click on File -> New -> Project and Select Console
Application.
2. Enter name for the project. Say TypedDataSetTest.

3. Right click on the solution and click on Add-> Add New Item will show a
dialog box.

Select DataSet from templates pane, give the name (Say TypedDs.xsd) and
click on Open. This will add file by name TypedDs.xsd to the solution.

4. Click on the Server Explorer browse to the database and drop the table on
the TypedDs.xsd file.

If we check the xml file for the same then we can see the schema for the
table.

This dataset can be used in the same manner as the normal dataset to get
the data.

C# ADO.NET DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter
provides the communication between the Datasetand 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
CS6001 C# AND .NET
PROGRAMMING

Unit
III

SQL operations , we are using the continuation of the Select


command perform by the DataAdapter.
TheSelectCommand property of the DataAdapter is a Command
Object that retrieves data from the data source.
TheInsertCommand , UpdateCommand ,
and DeleteCommandproperties 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. From
the following links describes how to use SqlDataAdapter
and OleDbDataAdapter in detail.

C# ADO.NET SqlDataAdapter
SqlDataAdapter Class is a part of the C# ADO.NET Data Provider
and it resides in the System.Data.SqlClient namespace.
SqlDataAdapter provides the communication between the Dataset
and the SQL database. We can use SqlDataAdapter Object in
combination with 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.
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(ds);

The SqlDataAdapter Object and DataSet objects are combine to


perform both data access and data manipulation operations in
theSQL Server Database. When the user perform the SQL
operations like Select , Insert etc. in the data containing in
the DatasetObject , it won't directly affect the Database, until the
user invoke the Update method in the SqlDataAdapter.
using
using
using
using

System;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;

namespace WindowsApplication1
{

CS6001 C# AND .NET


PROGRAMMING

Unit
III

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -" + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbDataAdapter
The OleDbDataAdapter is a part of the C# ADO.NET Data Provider
and it resides in the System.Data.OleDb namespace. The
OleDbDataAdapter provides the communication between the
Dataset and the OleDb Data Sources. We can use
OleDbDataAdapter Object in combination with Dataset Object.
DataAdapter provides this combination by mapping Fill method,
CS6001 C# AND .NET
PROGRAMMING

Unit
III

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.
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);

The OleDbDataAdapter Object and DataSet objects are combine


to perform both Data Access and Data Manipulation operations in
the OleDb Data Sources. When the user perform the SQL operations
like Select , Insert etc. in the data containing in theDataset
Object , it won't directly affect the Database, until the user invoke
the Update method in the OleDbDataAdapter.
using
using
using
using

System;
System.Windows.Forms;
System.Data;
System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
string sql = null;
int i = 0;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
oledbCnn = new OleDbConnection(connetionString);
try
{
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -" + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
oledbCnn.Close();
}

CS6001 C# AND .NET


PROGRAMMING

Unit
III

catch (Exception ex)


{
MessageBox.Show("Can not open connection ! ");
}
}

CS6001 C# AND .NET


PROGRAMMING

Unit
III

Insert, Delete, and Update using Stored


Procedure in ASP.NET
A stored procedure is nothing more than a prepared SQL code that you save so
you can reuse the code over and over again. So if you think about a query that you
write over and over again, instead of having to write that query each time you would
save it as a stored procedure and then just call the stored procedure to execute the
SQL code that you saved as part of the stored procedure.
SP is pre-define and pre-compiled set of souce code.
Basic Difference between Stored Procedure and Functions
1. Function must return a value, but in Stored Procedure it is optional (procedure
can return zero or n values).
2. Functions can have only input parameters for it, whereas procedures can
have input/output parameters.
3. Functions can be called from procedure, whereas procedures cannot be
called from function.
4. Procedure allows SELECT as well as DML (INSERT/UPDATE/DELETE)
statement in it whereas function allows only SELECT statement in it.
5. Stored procedure is precompiled execution plan whereas functions are not.
Note: Sometimes we face a question, why we can't execute stored procedure inside
a function?
Answer:
1. Stored Procedure may contain DML statements.
2. Function can't contain DML statements.
So executing function inside stored procedure will never break rule 1, but executing
stored procedure inside function may break rule 2.
So ultimately strict rule is made that we can't execute stored procedures inside
function.
First we have to create one Table. E.g. Registration
CS6001 C# AND .NET
PROGRAMMING

Unit
III

1.
2.
3.
4.
5.
6.

CREATE TABLE UserRegistration (


C_Id int IDENTITY(1, 1) NOT NULL,
C_Name varchar(100) NULL,
C_Age varchar(100) NULL,
C_Country varchar(100) NULL
);

After that we have to create one stored procedure. E.g. SpMyProcedure.


1.
2.
3.
4.
5.
6.
7.

Create procedure SpMyProcedure (


@Id int = null,
@Name varchar(100)= null,
@Age varchar(100)= null,
@Country varchar(100)= null,
@Action varchar(100)= null
) As begin if @Action = 'Insert' Insert into UserRegistration(C_Name, C_Age, C
_Country)
8. values
9. (@Name, @Age, @Country) if @Action = 'Update'
10. Update
11. UserRegistration
12. set
13. C_Name = @Name,
14. C_Age = @Age,
15. C_Country = @Countrywhere C_Id = @Id if @Action = 'Delete'
16. Delete from
17. UserRegistration
18. where
19. C_Id = @Id end

Now we can call stored procedure from our code like the following for Insert
operation.
1. protected void btnSave_Click(object sender, EventArgs e)
2. {
3.
string str = "server=Your Server Name; Initial Catalog=Your Database Name;
User ID=User Id; Password=Your Password";
4.
SqlConnection cn = new SqlConnection(str);
5.
SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6.
cmd.CommandType = CommandType.StoredProcedure;
7.
cmd.Parameters.AddWithValue("@Action", "Insert");
8.
cmd.Parameters.AddWithValue("@Name", txtName.Text);
9.
cmd.Parameters.AddWithValue("@Age", txtAge.Text);
10. cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
11. cn.Open();
12. cmd.ExecuteNonQuery();
13. cn.Close();
14. }

We can call stored procedure from our code like the following for Delete operation.
1. protected void btnDelete_Click(object sender, EventArgs e)
2. {

CS6001 C# AND .NET


PROGRAMMING

Unit
III

3.

string str = "server=Your Server Name; Initial Catalog=Your Database Name;


User ID=User Id; Password=Your Password";
4.
SqlConnection cn = new SqlConnection(str);
5.
SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6.
cmd.CommandType = CommandType.StoredProcedure;
7.
cmd.Parameters.AddWithValue("@Action", "Delete");
8.
cmd.Parameters.AddWithValue("@Id", txtId.Text);
9.
cn.Open();
10. cmd.ExecuteNonQuery();
11. cn.Close();
12. }

We can call stored procedure from our code like the following for Update operation.
1. protected void btnUpdate_Click(object sender, EventArgs e)
2. {
3.
string str = "server=Your Server Name; Initial Catalog=Your Database Name;
User ID=User Id; Password=Your Password";
4.
SqlConnection cn = new SqlConnection(str);
5.
SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6.
cmd.CommandType = CommandType.StoredProcedure;
7.
cmd.Parameters.AddWithValue("@Action", "Update");
8.
cmd.Parameters.AddWithValue("@Name", txtName.Text);
9.
cmd.Parameters.AddWithValue("@Age", txtAge.Text);
10. cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
11. cmd.Parameters.AddWithValue("@Id", txtId.Text);
12. cn.Open();
13. cmd.ExecuteNonQuery();
14. cn.Close();
15. }

C# SQL Server Connection


You can connect your C# application to data in a SQL Server
database using the .NET Framework Data Provider for SQL Server.
The first step in a C# application is to create an instance of the
Server object and to establish its connection to an instance of
Microsoft SQL Server.
The SqlConnection Object is Handling the part of physical
communication between the C# application and the SQL Server
Database . An instance of the SqlConnection class in C# is
supported the Data Provider for SQL Server Database. The
SqlConnection instance takes Connection String as argument and
pass the value to the Constructor statement.
Sql Server connection string
CS6001 C# AND .NET
PROGRAMMING

Unit
III

connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

If you have a named instance of SQL Server, you'll need to add that
as well.
"Server=localhost\sqlexpress"

When the connection is established , SQL Commands will execute


with the help of the Connection Object and retrieve or manipulate
the data in the database. Once the Database activities is over ,
Connection should be closed and release the Data Source resources
.
cnn.Close();

The Close() method in SqlConnection Class is used to close the


Database Connection. The Close method rolls back any pending
transactions and releases the Connection from the SQL Server
Database.
A Sample C# Program that connect SQL Server using connection
string.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)

CS6001 C# AND .NET


PROGRAMMING

Unit
III

{
MessageBox.Show("Can not open connection ! ");
}
}

Connect via an IP address


connetionString="Data Source=IP_ADDRESS,PORT;
Network Library=DBMSSOCN;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"

1433 is the default port for SQL Server.


Trusted Connection from a CE device
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=SSPI;
User ID=myDomain\UserName;Password=Password;

This will only work on a CE device


Connecting to SQL Server using windows authentication
"Server= localhost; Database= employeedetails;
Integrated Security=SSPI;"

A sample c# program that demonstrate how to execute sql


statement and read data from SQL server.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
string sql = null;
SqlDataReader dataReader ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";

CS6001 C# AND .NET


PROGRAMMING

Unit
III

sql = "Your SQL Statement Here , like Select * from product";


connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " +
dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

A sample C# program that perform Data Manipulation tasks like


Insert , Update , Delete etc. also perform by the ExecuteNonQuery()
of SqlCommand Object.

C# OLEDB Connection
The C# OleDbConnection instance takes Connection String as
argument and pass the value to the Constructor statement. An
instance of the C# OleDbConnection class is supported theOLEDB
Data Provider .
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);

When the connection is established between C# application and the


specified Data Source, SQL Commands will execute with the help of
the Connection Object and retrieve or manipulate data in the
database. Once the Database activities is over Connection should be
closed and release from the data source resources .
cnn.Close();

The Close() method in the OleDbConnection class is used to close


CS6001 C# AND .NET
PROGRAMMING

Unit
III

the Database Connection. The Close method Rolls Back any


pending transactions and releases the Connection from the
Database connected by the OLEDB Data Provider.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OleDbConnection cnn ;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ODBC Connection
An instance of the OdbcConnection Class in C# is supported the
ODBC Data Provider. The OdbcConnection instance takes
Connection String as argument and pass the value to the
Constructor statement. When the connection is established between
C# application and the Data Source the SQL Commands will execute
with the help of the Connection Object and retrieve or manipulate
data in the database.
CS6001 C# AND .NET
PROGRAMMING

Unit
III

connetionString = "Driver={Microsoft Access Driver (*.mdb)};


DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);

Once the Database activities is over you should be closed the


Connection and release the Data Source resources . The Close()
method in OdbcConnection Class is used to close the Database
Connection.
cnn.Close();

The Close method rolls back any pending transactions and releases
the Connection from the Database connected by theODBC Data
Provider .
using System;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
OdbcConnection cnn ;
connetionString = "Driver={Microsoft Access Driver
(*.mdb)};DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

CS6001 C# AND .NET


PROGRAMMING

Unit
III

C# ADO.NET Command
The Command Object in ADO.NET executes SQL statements and
Stored Procedures against the data source specified in the C#
Connection Object. The Command Object requires an instance of a
C# Connection Object for executing the SQL statements .
In order to retrieve a resultset or execute an SQL statement against
a Data Source , first you have to create a Connection Object and
open a connection to the Data Source specified in the connection
string. Next step is to assign the open connection to the connection
property of the Command Object . Then the Command Object can
execute the SQL statements. After the execution of the SQl
statement, the Command Object will return a result set . We can
retrieve the result set using a Data Reader.

The Command Object has a property called CommandText ,


which contains a String value that represents the command that will
be executed against the Data Source. When
theCommandType property is set to StoredProcedure, the
CommandText property should be set to the name of the stored
procedure.
Click the following links to see some important built in methods uses
in the Command Object to execute the SQL statements.
C# ExecuteNonQuery
C# ExecuteReader
CS6001 C# AND .NET
PROGRAMMING

Unit
III

C# ExecuteScalar

C# ADO.NET SqlCommand ExecuteNonQuery


The ExecuteNonQuery() is one of the most frequently used
method in SqlCommand Object, and is used for executing
statements that do not return result sets (ie. statements like insert
data , update data etc.) .
Command.ExecuteNonQuery();

The ExecuteNonQuery() performs Data Definition tasks as well as


Data Manipulation tasks also. The Data Definition tasks like creating
Stored Procedures ,Views etc. perform by
theExecuteNonQuery() . Also Data Manipulation tasks like Insert ,
Update , Delete etc. also perform by the ExecuteNonQuery() of
SqlCommand Object.
The following C# example shows how to use the method
ExecuteNonQuery() through SqlCommand Object.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
cnn = new SqlConnection(connetionString);

CS6001 C# AND .NET


PROGRAMMING

Unit
III

try
{

!!");

}
}

cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed

}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

How to C# ADO.NET OleDbCommand ExecuteNonQuery


The ExecuteNonQuery() is one of the most frequently used
method in OleDbCommand Object and is used for executing
statements that do not returns result sets. The ExecuteNonQuery()
performs Data Definition tasks as well as Data Manipulation tasks
also.
cmd.ExecuteNonQuery();

The Data Definition tasks like creating Stored Procedures, Views etc.
perform by the ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update , Delete etc. perform by the
ExecuteNonQuery().
The following C# example shows how to use the method
ExecuteNonQuery() through OleDbCommand Object.
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{

CS6001 C# AND .NET


PROGRAMMING

Unit
III

InitializeComponent();

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
OleDbCommand cmd ;
string sql = null;
connetionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here"
cnn = new OleDbConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Opened ");
cmd = new OleDbCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in OleDbConnection
executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " +
ex.ToString());
}
}
}
}

C# ADO.NET SqlCommand - ExecuteScalar


The ExecuteScalar() in C# SqlCommand Object is using for
retrieve a single value from Database after the execution of the SQL
Statement. The ExecuteScalar() executes SQL statements as well as
Stored Procedure and returned a scalar value on first column of first
row in the returned Result Set.
If the Result Set contains more than one columns or rows , it will
take only the value of first column of the first row, and all other
values will ignore. If the Result Set is empty it will return
a NULLreference.

It is very useful to use with aggregate functions


like Count(*) orSum() etc. When compare to ExecuteReader() ,
ExecuteScalar() uses fewer System resources.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statement Here like Select Count(*) from
product";

}
}

cnn = new SqlConnection(connetionString);


try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
cnn.Close();
MessageBox.Show (" No. of Rows " + count);
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
string sql = null;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed
!!");

}
}

}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}

79

Exception Handling
An exception is a problem that arises during the execution of a program. A
C# exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to
another.
C#
exception
handling
is
built
upon
four
keywords: try, catch, finally, and throw.

try: A try block identifies a block of code for which particular exceptions is
activated. It is followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a


program where you want to handle the problem. The catch keyword indicates the
catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done
using a throw keyword.

Syntax
Assuming a block raises an exception, a method catches an exception using a
combination of the try and catch keywords. A try/catch block is placed around
the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like
the following:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code

80

}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}

You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in different
situations.

Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are
mainly directly or indirectly derived from the System.Exception class. Some
of the exception classes derived from the System.Exception class are
theSystem.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by
application programs. Hence the exceptions defined by the programmers
should derive from this class.
The System.SystemException class is the base class for all predefined
system exception.
The following table provides some of the predefined exception classes derived
from the Sytem.SystemException class:
Exception Class

Description

System.IO.IOException

Handles I/O errors.

81

System.IndexOutOfRangeException

Handles errors generated when a method


refers to an array index out of range.

System.ArrayTypeMismatchException Handles errors generated when type is


mismatched with the array type.

System.NullReferenceException

Handles errors generated from deferencing a


null object.

System.DivideByZeroException

Handles errors generated from dividing a


dividend with zero.

System.InvalidCastException

Handles errors generated during typecasting.

System.OutOfMemoryException

Handles errors generated from insufficient


free memory.

System.StackOverflowException

Handles errors generated from stack


overflow.

Handling Exceptions
C# provides a structured solution to the exception handling in the form of try
and catch blocks. Using these blocks the core program statements are
separated from the error-handling statements.
These error handling blocks are implemented using the try, catch,
and finallykeywords. Following is an example of throwing an exception when
dividing by zero condition occurs:
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;

82

}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are
derived from the Exception class. The following example demonstrates this:
using System;
namespace UserDefinedException

83

{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}

public class TempIsZeroException: Exception


{
public TempIsZeroException(string message): base(message)
{
}
}

public class Temperature


{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else

84

{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}

When the above code is compiled and executed, it produces the following
result:
TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from
theSystem.Exception class. You can use a throw statement in the catch
block to throw the present object as:
Catch(Exception e)
{
...
Throw e
}

85

ASP.NET - Validators
ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.
ASP.NET provides the following validation controls:

RequiredFieldValidator

RangeValidator

CompareValidator

RegularExpressionValidator

CustomValidator

ValidationSummary

BaseValidator
Class
The validation control classes are inherited from the BaseValidator class
hence they inherit its properties and methods. Therefore, it would help to
take a look at the properties and the methods of this base class, which are
common for all the validation controls:
Members

Description

ControlToValidate

Indicates the input control to validate.

Display

Indicates how the error message is shown.

EnableClientScript

Indicates whether client side validation will take.

Enabled

Enables or disables the validator.

CS6001 C# AND .NET


PROGRAMMING

Unit
III

86

ErrorMessage

Indicates error string.

Text

Error text to be shown if validation fails.

IsValid

Indicates whether the value of the control is valid.

SetFocusOnError

It indicates whether in case of an invalid control, the focus


should switch to the related input control.

ValidationGroup

The logical group of multiple validators, where this control


belongs.

Validate()

This method revalidates the control and updates the


IsValid property.

RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not
empty. It is generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

CS6001 C# AND .NET


PROGRAMMING

Unit
III

87

RangeValidator
The RangeValidator control
Control

verifies that the input value falls within a

predetermined range.
It has three specific properties:
Properties

Description

Type

It defines the type of the data. The available values are:


Currency, Date, Double, Integer, and String.

MinimumValue

It specifies the minimum value of the range.

MaximumValue

It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.
It has the following specific properties:
Properties

CS6001 C# AND .NET


PROGRAMMING

Description

Unit
III

88

Type

It specifies the data type.

ControlToCompare

It specifies the value of the input control to compare with.

ValueToCompare

It specifies the constant value to compare with.

Operator

It specifies the comparison operator, the available values


are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

</asp:CompareValidator
>

RegularExpressionValidat
or
The RegularExpressionValidator allows validating the input text by matching
against a pattern of a regular expression. The regular expression is set in
the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for
regular expressions:
Character Escapes

Description

\b

Matches a backspace.

CS6001 C# AND .NET


PROGRAMMING

Unit
III

89

\t

CS6001 C# AND .NET


PROGRAMMING

Matches a tab.

Unit
III

90

\r

Matches a carriage return.

\v

Matches a vertical tab.

\f

Matches a form feed.

\n

Matches a new line.

Escape character.

Apart from single character match, a class of characters could be specified


that can be matched, called the metacharacters.
Metacharacters

Description

Matches any character except \n.

[abcd]

Matches any character in the set.

[^abcd]

Excludes any character in the set.

[2-7a-mA-M]

Matches any character specified in the range.

\w

Matches any alphanumeric character and underscore.

\W

Matches any non-word character.

CS6001 C# AND .NET


PROGRAMMING

Unit
III

91

\s

Matches whitespace characters like, space, tab, new line


etc.

\S

Matches any non-whitespace character.

\d

Matches any decimal character.

\D

Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could


appear.
Quantifier

Description

Zero or more matches.

One or more matches.

Zero or one matches.

{N}

N matches.

{N,}

N or more matches.

{N,M}

Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"

CS6001 C# AND .NET


PROGRAMMING

Unit
III

92

ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidato
r
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.
The

client

side

validation

is

accomplished

through

the

ClientValidationFunction property. The client side validation routine should


be written in a scripting language, such as JavaScript or VBScript, which the
browser can understand.
The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator
>

ValidationSummar
y
The ValidationSummary control does not perform any validation but shows
a summary of all errors in the page. The summary displays the values of
the ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
CS6001 C# AND .NET
PROGRAMMING

Unit
III

93

ShowSummary : shows the error messages in specified format.

ShowMessageBox : shows the error messages in a separate window.

CS6001 C# AND .NET


PROGRAMMING

Unit
III

94

The syntax for the control is as given:


<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

Validation
Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation
separately for separate group. This kind of situation is handled using
validation groups.
To create a validation group, you should put the input controls and the
validation

controls

into

the

same

logical

group

by

setting

their ValidationGroupproperty.

Exampl
e
The following example describes a form to be filled up by all the students of
a school, divided into four houses, for electing the school president. Here,
we use the validation controls to validate the user input.
This is the form in design view:

CS6001 C# AND .NET


PROGRAMMING

Unit
III

95

The content file code is as given:


<form id="form1" runat="server">

CS6001 C# AND .NET


PROGRAMMING

Unit
III

96

<table style="width: 66%;">

<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>

<tr>
<td class="style3">
Candidate:
</td>

<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"

CS6001 C# AND .NET


PROGRAMMING

Unit
III

97

ErrorMessage="Please choose a candidate"


InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>

<tr>
<td class="style3">
House:
</td>

<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>

<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >
</asp:RequiredFieldValidator>
<br />
</td>
</tr>

<tr>

CS6001 C# AND .NET


PROGRAMMING

Unit
III

98

<td class="style3">
Class:
</td>

<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>

<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>

<tr>
<td class="style3">
Email:
</td>

<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
</asp:TextBox>
</td>

<td>
<asp:RegularExpressionValidator ID="remail" runat="server"

CS6001 C# AND .NET


PROGRAMMING

Unit
III

99

ControlToValidate="txtemail" ErrorMessage="Enter your email"


ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>

<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
</form>

The code behind the submit button:


protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblmsg.Text = "Thank You";
}
else
{
lblmsg.Text = "Fill up all the fields";
}
}

CS6001 C# AND .NET


PROGRAMMING

Unit
III

100

Simplest way to have a configuration file in a


Windows Forms C# Application
1) Add a new file to your project (Add->New Item->Application Configuration File)
2) The new config file will appear in Solution Explorer as App.Config.
3) Add your settings into this file using the following as a template
<configuration>
<appSettings>
<add key="setting1" value="key"/>
</appSettings>
<connectionStrings>
<add name="prod" connectionString="YourConnectionString"/>
</connectionStrings>
</configuration>

4) Right click the project in Solution Explorer then select the Add references and
then select .Net tab. Select The System.Configuration Click Ok.
5)Retrieve them like this :
private void Form1_Load(object sender, EventArgs e)
{
string setting = ConfigurationManager.AppSettings["setting1"];
string conn =
ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
}

6) When built, your output folder will contain a file called


<assemblyname>.exe.config This will be a copy of the App.Config file. No further
work should need to be done by the developer to create this file.

Unit
III

101

UPDATING DATABASE USING STORED


PROCEDURES

C# Stored Procedure with Parameter


The .NET Data Providers consist of a number of classes used to connect to a
data source, execute commands, and return recordsets. The Command Object
in ADO.NET provides a number of Execute methods that can be used to
perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or
more SQL statements. In many cases stored procedures accept input
parameters and return multiple values . Parameter values can be supplied if a
stored procedure is written to accept them. A sample stored procedure with
accepting input parameter is given below :
CREATE PROCEDURE SPPUBID
@PubID VARCHAR(20), @Address VARCHAR(50)
AS
UPDATE publishers SET Pub_Address=@Address WHERE PubID = @PubID
GO

The above stored procedure is accepting a publishers ID (@PubID


VARCHAR(20)) and (@Address VARCHAR(50)) as parameter and update the
publishers address from the input publisher ID. Once the CommandType is set
to StoredProcedure, you can use the Parameters collection to define
parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@PubID", "P0001");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
param1 = new SqlParameter("@Address", "CHENNAI");
param1.Direction = ParameterDirection.Input;
param1.DbType = DbType.String;

command.Parameters.Add(param);
command.Parameters.Add(param1);

The above code passing publisher ID and publisher Address parameters to


the stored procedure from C# application.
Unit
III

102

using
using
using
using

System;
System.Data;
System.Windows.Forms;
System.Data.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
SqlParameter param1 ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial
Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPPUBID";
param = new SqlParameter("@PubID", "P0001");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
param1 = new SqlParameter("@Address","CHENNAI");
param1.Direction = ParameterDirection.Input;
param1.DbType = DbType.String;
command.Parameters.Add(param1);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString
());

Unit
III

103

}
}

connection.Close();

Ref :
https://msdn.microsoft.com/
libr ar y
https://en.wikipedia.org
http://www.functionx.com/vcsharp2008/form/dialogboxes3.htm
http://www.dotnetperls.com/dataset-vbnet
http://www.csharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedD
ataSets.aspx

http://www.c-sharpcorner.com/blogs/insert-delete-and-update-using-storedprocedure-in-asp-net1

Unit
III

You might also like