cs6001 C# Unit 3
cs6001 C# Unit 3
cs6001 C# Unit 3
_______________________________________________________________________
UNIT III
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
services such as
security, memory management, and exception handling. FCL and CLR together constitute .NET
Framework.
FCL
provides user
interface, data
access, database
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.
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.
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
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:
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
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.
C#
using System;
using System.Windows.Forms;
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);
}
}
9
}
10
green = new Button();
green.Text = "Green";
green.Location = new Point(100, 150);
// 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
Walkthrough: Displaying a
Menu on Web Pages
.NET Framework 4
Other Versions
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.
15
15
16
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.
17
18
19
url="Consulting.aspx" />
<siteMapNode title="Support"
description="Support plans"
url="Support.aspx" />
</siteMapNode>
</siteMapNode>
</siteMap>
5.Save the file.
20
With your pages and menu in place, you can try it out.
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
22
23
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.
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.
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.
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.
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.
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
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.
30
31
It can be neither minimized nor maximized. This means that it is not equipped with
the Minimize or the Maximize buttons
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
On the main menu, you can click Window and click the
name of the form in the list under Close All Documents
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.
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
3.
4. Create a property
5.
Press Enter
34
35
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.
37
38
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
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
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.
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
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
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
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
Using SqlParameters gives a cleaner, less error prone and SQL injection safe
(comparative) code.
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;
}
Copy Code
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;
}
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.
<id>1</id>
<medication>atenolol</medication>
</medications>
<medications>
<id>2</id>
<medication>amoxicillin</medication>
</medications>
</office>
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()
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
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.
//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.
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.
Unit
III
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);
System;
System.Windows.Forms;
System.Data;
System.Data.SqlClient;
namespace WindowsApplication1
{
Unit
III
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);
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();
}
Unit
III
Unit
III
Unit
III
1.
2.
3.
4.
5.
6.
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. {
Unit
III
3.
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. }
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"
Unit
III
{
MessageBox.Show("Can not open connection ! ");
}
}
Unit
III
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);
Unit
III
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
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 ! ");
}
}
}
}
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.
Unit
III
C# ExecuteScalar
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 ! ");
}
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()
{
Unit
III
InitializeComponent();
}
}
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.
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
81
System.IndexOutOfRangeException
System.NullReferenceException
System.DivideByZeroException
System.InvalidCastException
System.OutOfMemoryException
System.StackOverflowException
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
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();
}
}
}
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
Display
EnableClientScript
Enabled
Unit
III
86
ErrorMessage
Text
IsValid
SetFocusOnError
ValidationGroup
Validate()
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>
Unit
III
87
RangeValidator
The RangeValidator control
Control
predetermined range.
It has three specific properties:
Properties
Description
Type
MinimumValue
MaximumValue
</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
Description
Unit
III
88
Type
ControlToCompare
ValueToCompare
Operator
</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.
Unit
III
89
\t
Matches a tab.
Unit
III
90
\r
\v
\f
\n
Escape character.
Description
[abcd]
[^abcd]
[2-7a-mA-M]
\w
\W
Unit
III
91
\s
\S
\d
\D
Description
{N}
N matches.
{N,}
N or more matches.
{N,M}
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
</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
Unit
III
94
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:
Unit
III
95
Unit
III
96
<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"
Unit
III
97
<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>
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"
Unit
III
99
<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>
Unit
III
100
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;
}
Unit
III
101
command.Parameters.Add(param);
command.Parameters.Add(param1);
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