Ado Unit 3
Ado Unit 3
Windows Forms is a Graphical User Interface (GUI) class library which is bundled in .Net Framework.
Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs.
It is also termed as the WinForms. The applications which are developed by using Windows Forms or
WinForms are known as the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms Applications not web applications.
WinForms applications can contain the different type of controls like labels, list boxes, tooltip etc.
First, open the Visual Studio then Go to File -> New -> Project to create a new project and
then select the language as Visual C# from the left menu. Click on Windows Forms App(.NET
Framework) in the middle of current window. After that give the project name and Click OK.
Here the solution is like a container which contains the projects and files that may be
required by the program.
After that following window will display which will be divided into three parts as follows:
1. Editor Window or Main Window: Here, you will work with forms and code editing.
You can notice the layout of form which is now blank. You will double click the form
then it will open the code for that.
2. Solution Explorer Window: It is used to navigate between all items in solution. For
example, if you will select a file form this window then particular information will be
display in the property window.
3. Properties Window: This window is used to change the different properties of the
selected item in the Solution Explorer. Also, you can change the properties of
components or controls that you will add to the forms.
Now to add the controls to your WinForms application go to Toolbox tab present in the
extreme left side of Visual Studio. Here, you can see a list of controls. To access the most
commonly used controls go to Common Controls present in Toolbox tab.
Now drag and drop the controls that you needed on created Form. For example, if you can
add TextBox, ListBox, Button etc. as shown below. By clicking on the particular dropped
control you can see and change its properties present in the right most corner of Visual
Studio.
In the above image, you can see the TextBox is selected and its properties like TextAlign,
MaxLength etc. are opened in right most corner. You can change its properties’ values as per
the application need. The code of controls will be automatically added in the background.
You can check the Form1.Designer.cs file present in the Solution Explorer Window.
To run the program you can use an F5 key or Play button present in the toolbar of Visual
Studio. To stop the program you can use pause button present in the ToolBar. You can also
run the program by going to Debug->Start Debugging menu in the menubar.
C# Windows Forms is a graphical user interface (GUI) framework that enables developers to create
desktop applications for the Windows operating system. Windows Forms applications are created
using the C# programming language and the .NET framework. They are built by dragging and
dropping controls such as buttons, text boxes, labels, and other user interface elements onto a form.
1. The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar user
interface for Windows users. Developers can customize the appearance and behavior of
these controls by setting various properties and handling events.
2. To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is
an integrated development environment (IDE) that provides a visual designer to create and
layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.
3. In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events and
perform tasks such as data validation, data manipulation, and business logic implementation.
4. Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.
Introduction to ADO.NET
The .NET Framework includes its own data access technology i.e. ADO.NET. ADO.NET is the latest
implementation of Microsoft’s Universal Data Access strategy. ADO.NET consists of managed classes
that allows .NET applications to connect to data sources such as Microsoft SQL Server, Microsoft
Access, Oracle, XML, etc., execute commands and manage disconnected data..t
Microsoft ADO.NET is the latest improvement after ADO. Firstly, ADO.NET was introduced in the
10th version of the .NET framework, which helps in providing an extensive array of various features to
handle data in different modes, such as connected mode and disconnected mode. In connected
mode, we are dealing with live data and in disconnected mode, data is provided from the data store.
ADO.NET was primarily developed to address two ways to work with data that we are getting from
data sources. The two ways are as follows :
1. The first is to do with the user’s need to access data once and to iterate through a collection
of data in a single instance i.e caching the data in runtime memory.
2. The second way to work with data is in connected way which is we do not cache data. And
we always go to database to retrieve it
Architecture of ADO.NET :
ADO.NET uses a multilayered architecture that revolves around a few key concepts as –
asConnection
Command
DataSet objects
The ADO.NET architecture is a little bit different from the ADO, which can be shown from the
following figure of the architecture of ADO.NET.
Architecture of ADO.NET
One of the key differences between ADO and ADO.NET is how they deal with the challenge of
different data sources. In ADO.NET, programmers always use a generic set of objects, no matter what
the underlying data source is. For example, if we want to retrieve a record from an Oracle Database,
we use the same connection class that we use to tackle the same task with SQL Server. This is not the
case with ADO.NET, which uses a data provider model and the DataSet.
Features of ADO.NET :
The following are the features of ADO.NET –
Interoperability-
We know that XML documents are text-based formats. So, one can edit and edit XML
documents using standard text-editing tools. ADO.NET uses XML in all data exchanges and
for internal representation of data.
Maintainability –
ADO.NET is built around the idea of separation of data logic and user interface. It means that
we can create our application in independent layers.
Performance –
It uses disconnected data architecture which is easy to scale as it reduces the load on the
database. Everything is handled on the client-side, so it improves performance.
Scalability –
It means meeting the needs of the growing number of clients, which degrading performance.
As it uses disconnected data access, applications do not retain database lock connections for
a longer time. Thus, it accommodates scalability by encouraging programmers to conserve
limited resources and allow users to access data simultaneously.
ADO.NET is used in various applications where data access and manipulation are crucial. Here are
some types of applications that commonly use ADO.NET:
Desktop Applications: Traditional desktop applications like Windows Forms and WPF
applications often need to interact with databases or other data sources. ADO.NET provides
the necessary tools to connect to databases, retrieve data, and update records.
Web Applications: Web applications, including ASP.NET Web Forms and ASP.NET MVC
applications, require data access to display, collect, and manage information. ADO.NET
enables these applications to connect to databases and present data to users.
Console Applications: Console applications might need to perform data-related tasks, like
importing/exporting data, data analysis, or reporting. ADO.NET can facilitate these tasks by
providing efficient data access.
Service Applications: Background or Windows services that process data often rely on
ADO.NET to connect to databases and handle data-related operations.
C# Grid Control
SourceGrid is a Windows Forms control written entirely in C#, my goal is to create a simple but
flexible grid to use in all of the cases in which it is necessary to visualize or to change a series of data
in a table format. There are a lot of controls of this type available, but often are expensive, difficult to
be customize or not compatible with. NET. The Microsoft DataGrid for me is too DataSet orientated
and therefore results often complicated to use in the cases in which the source data isn't a DataSet
and often is not enough customizable.
In C#, binding a DataGridView to a data source involves setting the DataSource property to
an IEnumerable implementation (like a DataTable or List), and optionally specifying a DataMember if
the source has multiple tables/lists.
Purpose:
Data binding allows a DataGridView control to display and interact with data from various sources
(databases, collections, etc.).
Mechanism:
DataTable
DataSet
List<T>
BindingSource
The DataGridView can be configured to respond to events related to data changes (e.g., row added,
cell changed).
2. Binding to a DataTable
example.
// Create a DataTable
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dataGridView1.DataSource = dt;
Explanation:
3. Binding to a List
example.
dataGridView1.DataSource = people;
Explanation:
example.
// Create a BindingSource
// Create a DataTable
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
bs.DataSource = dt;
dataGridView1.DataSource = bs;
Explanation:
Column Headers: The DataGridView automatically creates column headers based on the
data source's column names. You can customize these headers by setting
the HeaderText property of the DataGridViewColumn objects.
Column Formatting: You can format the data displayed in each column using
the DefaultCellStyle property of the DataGridViewColumn objects.
Sorting and Filtering: The DataGridView provides built-in sorting and filtering capabilities.
Data Binding
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which
gives it an inherent capability to bind data to at least one of its properties. This is known as simple
data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the
control.
On the other hand, some controls can bind records, lists, or columns of data into their structure
through a DataSource control. These controls derive from the BaseDataBoundControl class. This is
called declarative data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
DataBoundControl
HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
ListControl
CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these
controls are:
BulletedList
CheckBoxList
DropDownList
ListBox
RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the
abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView
GridView
RecordList
Simple Data Binding
Simple data binding involves the read-only selection lists. These controls can bind to an array list or
fields from a database. Selection lists takes two values from the database or the data source; one
value is displayed by the list and the other is considered as the value corresponding to the display.
Let us take up a small example to understand the concept. Create a web site with a bulleted list and a
SqlDataSource control on it. Configure the data source control to retrieve two values from your
database (we use the same DotNetReferences table as in the previous chapter).
Choosing a data source for the bulleted list control involves:
Selecting the data source control
Selecting a field to display, which is called the data field
Selecting a field for the value
When the application is executed, check that the entire title column is bound to the bulleted list and
displayed.
Declarative Data Binding
We have already used declarative data binding in the previous tutorial using GridView control. The
other composite data bound controls capable of displaying and manipulating data in a tabular
manner are the DetailsView, FormView, and RecordList control.
In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET.
However, the data binding involves the following objects:
Example
Let us take the following steps:
Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in
the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as
booklist.cs.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();
if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";
this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";
this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";
this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";
this.DataBind();
}
}
return allbooks;
}
The Adapter Design Pattern is a structural pattern that allows objects with incompatible interfaces to
work together. It acts as a bridge between two incompatible interfaces. This pattern is useful when
you want to use existing classes, but their interfaces do not match the one you need.
The Adapter Design Pattern acts as a bridge between two incompatible objects. Let’s say the first
object is A and the second object is B. Object A wants to consume some of object B’s services.
However, these two objects are incompatible and cannot communicate directly. In this case, the
Adapter will come into the picture and act as a middleman or bridge between objects A and B. Now,
object A will call the Adapter, and the Adapter will do the necessary transformations or conversions,
and then it will call object B.
Let us understand the Adapter Design Pattern with an Example, and then we will see the UML
Diagram of the Adapter Design Pattern by comparing it with our Example. Please have a look at the
following image. Here, you can see two interfaces, or you can say two systems. On the right-hand
side, you can see the Third Party Billing System; on the left-hand side, you can see the Client, i.e., the
Existing HR System. Now, we will see how these two systems are incompatible, and we will also see
how we will make them compatible using Adapter Design Patterns in C#.
Now, the HR System will send the employee information as a String Array to the Adapter. Then, what
this Adapter will do is it will read the employee information from the string array, populate the
employee object, and then put each employee object into the List<Employee> collection. Then, the
Adapter will send the List<Employee> to the ProcessSalary method of the Third Party Billing System.
Then, the ProcessSalary method calculates each employee’s salary and deposits the salary into the
Employee’s bank account.
So, in this way, we can make two incompatible interfaces work together with the help of the Adapter
Design Pattern in C#. Again, the Adapter Design Pattern in C# can be implemented in two ways. They
are as follows.
1. Object Adapter Pattern
2. Class Adapter Pattern
Implementation of Object Adapter Design Pattern in C#:
Let us implement the example we discussed using the Object Adapter Design Pattern in C# step by
step. Once we discuss the Example, we will see the UML Diagram of the Object Adapter Design
Pattern by comparing it with our Examples. So, let us proceed and see how we can implement the
Object Adapter Design Pattern in C#.
Step 1: Creating Employee Class
Create a class file named Employee.cs and copy and paste the following code. This class is going to be
used by ThirdPartyBillingSystem (i.e., Adaptee) as well as by the Adapter. Here, we created the
Employee with the required properties and then initialize the properties using the class constructor.
namespace AdapterDesignPattern
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public decimal Salary { get; set; }
//The following will accept the employees in the form of string array
//Then convert the employee string array to List of Employees
//After conversation, it will call the Adaptee's Method to Process the Salaries
public void ProcessCompanySalary(string[,] employeesArray)
{
string Id = null;
string Name = null;
string Designation = null;
string Salary = null;
Console.Read();
}
}
}
Output:
The Adapter Design Pattern is composed of four components. They are as follows:
1. Client: The Client class can only see the ITarget interface, i.e., the class that implements the
ITarget interface, i.e., the Adapter (in our example, it is the EmployeeAdapter). Using that
Adapter (EmployeeAdapter) object, the client will communicate with the Adaptee, which is
incompatible with the client.
2. ITarget: This is going to be an interface that needs to be implemented by the Adapter. The
client can only see this interface, i.e., the class which implements this interface.
3. Adapter: This class makes two incompatible interfaces or systems work together. The
Adapter class implements the ITrager interface and provides the implementation for the
interface method. This class is also composed of the Adaptee, i.e., it has a reference to the
Adaptee object as we are using the Object Adapter Design Pattern. In our example, the
EmployeeAdapter class implements the ITarget Interface and provides implementations to
the ProcessCompanySalary method of the ITarget Interface. This class also has a reference to
the ThirdPartyBillingSystem object.
4. Adaptee: This class contains the client’s required functionality but is incompatible with the
existing client code. So, it requires some adaptation or transformation before the client can
use it. It means the client will call the Adapter, and the Adapter will do the required
conversions and then make a call to the Adaptee.
This is all about the Object Adapter Design Pattern in C#. Let us proceed and see how to achieve the
same using the Class Adapter Design Pattern in C#.
Understanding Class Adapter Design Pattern in C#:
This is another approach to implementing the Adapter Design Pattern in C#. In this approach, the
Adapter calls will implement the ITarget interface and inherit from the Adaptee class. That means the
Adapter class will now be a child of the Adaptee class. So, instead of creating a reference variable of
Adaptee to call the Adaptee method, it can call that method directly as it is available via inheritance.
Before implementing the same example using the Class Adapter Design Pattern, let us first
understand the class diagram of the Class Adapter Design Pattern. Please have a look at the following
image.
The class diagram is identical to the Object Adapter Design Pattern class diagram. The only difference
is that the Adapter class now implements the Target interface and is inherited from the Adaptee
class. In the case of the Object Adapter Design Pattern, the adapter has a reference to the Adaptee
object, and using that reference, it will call the adaptee methods. But in the case of the Class Adapter
Design Pattern, the adapter will call the inherited method of the Adaptee class directly.
Implementation of Class Adapter Design Pattern in C#:
Let us implement the previous example using the Class Adapter Design Pattern in C# step by step.
The implementation is exactly the same as the Object Adapter Design Pattern Implementation. The
only difference is in the EmployeeAdapter class. Now, in the EmployeeAdapter class, instead of
Creating a reference variable of the ThirdPartyBillingSystem class, we will make this
EmployeeAdapter class inherit from the ThirdPartyBillingSystem. After the required transformation
or conversations, we need to call the ProcessSalary method.
So, please modify the EmployeeAdapter class as shown below to use the Class Adapter Design
Pattern in C#. The EmployeeAdapter class is now inherited from the Adaptee, i.e., the
ThirdPartyBillingSystem class, and implements the ITarget interface.
using System;
using System.Collections.Generic;
namespace AdapterDesignPattern
{
// This is the class that makes two incompatible interfaces or systems work together.
// The Adapter makes the Adaptee's interface compatible with the Target's interface.
// To use Class Adapter Pattern, we need to inherit the Adapter class from the Adaptee class
public class EmployeeAdapter : ThirdPartyBillingSystem, ITarget
{
//The following will accept the employees in the form of string array
//Then convert the employee string array to List of Employees
//After conversation, it will call the Adaptee's Method to Process the Salaries
public void ProcessCompanySalary(string[,] employeesArray)
{
string Id = null;
string Name = null;
string Designation = null;
string Salary = null;
DataReader C#
Data reader is an object that is used to read data from the data sources. This can only perform read
operation and not update operation on the data source. The data is retrieved as a data stream from
the data source. Though the data reader is restricted in terms of only reading operation, it is highly
effective and optimized as it is read only and forward only. There are two types of providers in
the .Net Framework, they are SQLDataReader and OleDbDataReader. The data reader increases the
application performance by reducing system overhead as it stores the only row in memory at a given
point of time. This article will cover in detail the data reader in c# along with appropriate examples.
Syntax:
The sql data reader is available in the namespace System.Data.SqlClient and the corresponding
assembly is System.Data.SqlClient.dll. A SQL data reader is initialized as follows.
SqlDataReadersqlReader = sqlCmd.ExecuteReader();
The execute reader is used to pass the SQL statements or procedure to the sqlconnection object and
the corresponding result is stored in the sqlreader object of SqlDataReader. Before reading from any
data reader, it should always be open and should point to the first record. The read() method of data
reader is used to read and it moves forward to the next row.
The oledb data reader also behaves in the same way. It is available in the name space
System.Data.OleDb and the corresponding assembly is System.Data.OleDb.dll. An oledbDataReader
object is used to connect to OLEDB data sources and fetch data from them. Like SQLDataReader,
oledbdata reader should also be open before performing read operation. An oledb data reader is
initialized as follows.
OleDbDataReaderoledbReader = oledbCmd.ExecuteReader();
Accessing Data Reader Results
The data reader object has a read method that can be used to access rows from the result set. Each
column value can be accessed either using their name or using their column order in which they
appear on the result set. To improve efficiency, a set of pre-defined type conversion methods to
access values as such. Data reader is advised to use when working large sets of data as the data is not
stored in cache memory. It is always advisable to close the data reader object once it is used. If the
command has some return values or output parameters, it is only available once the data reader is
closed. Another important thing to keep in mind while using data reader is that when a connection is
used by a data reader another data reader or any other operation can’t be performed on that
connection. Also, one important thing to remember is only forward accessing the dataset is possible.
We can iterate to the next record only and not to the previous one.
Working with Multiple Sets
If data reader returns multiple result sets, the NextResult method of data reader can be used to
access them. During implementation, it should be noted and taken care that all the result sets are
being iterated and each column inside the result set is accessible.
Example #2
Code:
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace test
{
public partial class test : Form
{
public test()
{
InitializeComponent();
}
Public static void main()
{
string constr = null;
OleDbConnectionocon ;
OleDbCommandocmd ;
string sql = null;
constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb";
sql = "select * from emp";
ocon = new OleDbConnection(constr);
try
{
ocon.Open();
ocmd = new OleDbCommand(sql, ocon);
OleDbDataReaderordr = ocmd.ExecuteReader();
while (ordr.Read ())
{
Console.WriteLine("EmpName:" ordr.GetValue(0) + "Empage:" ordr.GetValue(1) + "Esalary"
ordr.GetValue(2) );
}
ordr.Close();
ocmd.Dispose();
ocon.Close();
}
catch (Exception ex)
{
Console.WriteLine("Connection Failed");
}
}
}
}
Output: