Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views59 pages

Notes of

ADO.NET is a technology for database communication in .NET applications, utilizing a disconnected model to fetch and manipulate data. The process of accessing a database involves creating connection and command objects, executing SQL statements, and managing connections. Key components include DataReader for reading data, DataAdapter for data manipulation, and DataSet for holding multiple DataTables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views59 pages

Notes of

ADO.NET is a technology for database communication in .NET applications, utilizing a disconnected model to fetch and manipulate data. The process of accessing a database involves creating connection and command objects, executing SQL statements, and managing connections. Key components include DataReader for reading data, DataAdapter for data manipulation, and DataSet for holding multiple DataTables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 59

1

ADO.NET
ADO.NET is a new evolution of ADO ( ActiveX Data Object ) technology. ADO.NET
technology is a disconnected model. It means, it connects to the database when
required, fetches the information and then gets disconnected. ADO.NET is a model
used by .NET application to communicate with a database for retrieving, accessing and
updating the data. With the help of ADO.NET we can retrieved from one data source
and saved its into another database.

Creating Connection for accessing the database :

There are maximum five steps for creating a connection and accessing the database
is:
(i) Creating a connection object
(ii) Creating a command object
(iii) Opening a connection
(iv) Execute an sql statement in the command object
(v) Close the connection

(i) Creating a Connection Object :


To establish a connection with a data source we must first create a
connection object and then provide a “ConnectionString” for this
object.
The “ConnectionString” property gets various parameters for
establishing a new connection i.e :

(a) “ Data Source ” or “Server ” : It is used to specify the name of


the server to be used when a connection is open.

(b) “ Initial Catalog ” or “Database ” : It is used to specify the


name of the database.

(c) “Integrated Security ” : It is used to determine the current


windows accounts are used for authentication. Its value may
be :--- true / false / yes / no / sspi(Security Support Provider
Interface ) which is equivalent to true.
2

(d) “User Id ” and “Password ” : It is used to specify the server


login account and its password.

(e) “Provider ” : It is used to set the name of the provider for the
connection. This parameter is used only in the
“ConnectionString ” property of the “ OledbConnection ”
class , not for “ SqlConnection ” class.
For Example :

Creating a connection Object for SQL Server database


Using System.Data.SqlClient;

SqlConnection con = new SqlConnection ( “Data


Source = Server_name ; Initial Catalog =
Database_name; Integrated Security = sspi “ ) ;

“ OR ”
SqlConnection con = new SqlConnection ( “
Server = Server_name ; Database = Database_name
; Integrated Security = sspi “) ;

“ OR ”
SqlConnection con = new SqlConnection ( “
Server = Server_name ; Database = Database_name
; User Id = user_name ; Password = password “) ;

“ OR ”
SqlConnection con = new SqlConnection ( ) ;

String str = “ Data Source = Server_name ;


Initial Catalog = Database_name ; Integrated
Security = sspi “ ;
con.ConnectionString = str ;
3

Creating a connection for MS Access


database
Using System.Data.Oledb;

OledbConnection con = new OledbConnection (“Provider


=microsoft.jet.oledb.4.0;data source = c: \\ ranjit \\
mydatabase_name.mdb ; “ ) ;

“OR”
OledbConnection con = new OledbConnection ( “
Provider = microsoft.jet.oledb.4.0 ; data source =
c: / ranjit / mydatabase_name.mdb ; User id ; Password
“ ) ;

Creating connection for SqlServer


using Oledb
OledbConnection con = new OledbConnection (“Provider
=SQLOLEDB ; data source = database_name;integrated
security=sspi“);

“OR”

OledbConnection con = new OledbConnection (“Provider


=SQLOLEDB; data source = database_name;user id
=user_name; password=password“) ;

Creating a connection for Oracle


Database
4

OledbConnection con = new OledbConnection (“Provider


=MSDAORA ; data source = ORCL; user id=scott;
password=tiger“);

(ii) Creating a Command Object : The Command


object specifies the sql statements that need to be
executed and the connection that need to be used to
execute these statements. We can execute SQL
statements or stored procedure through command
objects.
The following code demonstrates, how to
execute a command object:--

SqlCommand cmd = new SqlCommand (“SQL Query“ , con_Obj_name );

For Example:
SqlCommand cmd1= new SqlCommand(“Insert into
table1(roll,name) values(‘101’,’ranjit’)”,con);

SqlCommand cmd2= new SqlCommand(“update table1 set


name=’rishu’ where roll=’101’ ”,con);

SqlCommand cmd3= new SqlCommand(“delete from table1 where


roll=’101’ ”,con);

SqlCommand cmd4=new SqlCommand(“Select * from table1“, con);

(iii) Opening Connection : The “Open()” method uses to


connect to the data source and establish a connection.

Syntax: Connection_object_name.Open( ) ;

Example : con.open( ) ;

(iv) Execute an SqlStatements : After we have defined the


command , we need to execute it. The command class provides the
following execute methods:
5

 ExecuteReader() : This method executes the Command and


returns a value “DataReader” class type object depending on the
provider in use. This function is used for only “select” statement.

 ExecuteNonQuery() : This method is commonly used for INSERT,


UPDATE or DELETE statements. ExecuteNonQuery() method returns an
“int” type value that is the number of rows affected by the command.

For Example:
int n=cmd.ExecuteNonQuery();// In the case of
insert/update/delete
SqlDataReader dr=cmd.ExecuteReader();// In the case of
select

(v) Closing the Connection : After executing the commands


that we should close the connection by using the “Close()” method.

Syantx : Con_obj_name.Close ( ) ;

Example : con.Close( ) ;

Example of using ExecuteNonQuery ( ), ExecuteReader( ) and Execute Scalar( ) :


using System;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication2
{
class first
{
OleDbConnection con = new OleDbConnection("provider=
microsoft.jet.oledb.4.0; data source=c:/mydatabase1.mdb");

public void insert()


{
String nm, c_no;
Console.WriteLine("Enter name : ");
nm = Console.ReadLine();
Console.WriteLine("Enter Contac No : ");
c_no = Console.ReadLine();
OleDbCommand cmd = new OleDbCommand("Insert into table1(name,
contact) values('" + nm + "','" + c_no + "')", con);
con.Open();
6

int r = cmd.ExecuteNonQuery();
if (r == 1)
{
Console.WriteLine("Successfully inserted value");
}
else
{
Console.WriteLine("Value not inserted");
}
con.Close();
}
public void display()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from table1", con);
OleDbDataReader dr = cmd.ExecuteReader();
Console.Clear();

Console.WriteLine("================================");
Console.WriteLine("SL. No \t Cust Name \t Contact");

Console.WriteLine("================================");
while (dr.Read())
{
Console.WriteLine(dr[0].ToString() + "\t" + dr[1].ToString()+"\t\t"+dr[2].ToString());
}
Console.WriteLine("\n\n================================");
con.Close();
}
public void count()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select Count(*) from table1", con);
String c=cmd.ExecuteScalar().ToString();
Console.WriteLine("Total number of records is : " + c);
con.Close();
}
}
class Program
{
static void Main(string[] args)
{
int i=0;
first f1 = new first();
do
{
Console.WriteLine("1. Insert");
Console.WriteLine("2. Display");
Console.WriteLine("3. Count Record");
Console.WriteLine("4. Exit");
Console.WriteLine("Enter any choice (1/2/3) : ");
i=Int32.Parse(Console.ReadLine());
if (i == 1)
7

{
f1.insert();
}
else if (i == 2)
{
f1.display();
}
else if (i == 3)
{
f1.count();
}
}while(I < 4);
}
}

Example :--

Inserting value using cmd.AddWithValue() method : This is the important


function of command class for using the insert, update, Delete and display the record.

public void insert()


{
String nm, c_no;
Console.WriteLine("Enter name : ");
nm = Console.ReadLine();
Console.WriteLine("Enter Contac No : ");
c_no = Console.ReadLine();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Insert into table1(name,contact)values(@nm,@c_no)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@nm", nm);
cmd.Parameters.AddWithValue("@c_no", c_no);
cmd.ExecuteNonQuery();
con.Close();
}
Inserting value using cmd.Add ( ) method :
public void insert()
{
String nm, c_no;
Console.WriteLine("Enter name : ");
nm = Console.ReadLine();
Console.WriteLine("Enter Contac No : ");
c_no = Console.ReadLine();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "Insert into table1(name,contact)values(@nm,@c_no)";
cmd.Connection = con;
OleDbParameter param1=new OleDbParameter("@nm",nm);
OleDbParameter param2=new OleDbParameter("@c_no",c_no);
8

cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);

cmd.ExecuteNonQuery();
con.Close();
}
1. (ii) <provider>DataReader Class :  The “DataReader” class
inherited from the “IDataReader” class. A DataReader is the simplest and
fastest way of selecting some data from a data source.we can not directly
instantiate of DataReader object it means we can not use new keyword for
creating the object of DataReader. The DataReader is forword-only and read-
only stream from of data from the database. The DataReader retrieving data as
only one record is brought into memory at a time. The dr.Read( ) method will
advance to the next record in the stream.

There are some important Properties of “DataReader“ :

 HasRows :Gets a value that indicates whether the DataReader contains one or
more rows.
 FieldCount ::Gets the number of columns in the current row.
 IsClosed : Indicates whether the DataReader is closed or not.

For Example
public void diaply()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from stud_info", con);
SqlDataReader dr = cmd.ExecuteReader();
“Or”
IDataReader dr=cmd.ExecuteReader();
while (dr.Read())
{
Console.Write(dr.GetString(0) + "\t");
Console.Write(dr.GetValue(1) + "\t");
Console.Write(dr.GetInt32(2) + "\t");
Console.Write( dr.GetDateTime(3).ToShortDateString() + "\n");
}
Console.ReadLine();
Con.Close( );
}

DataAdapter: The DataAdapter classes inherit


from the IDbDataAdapter interface and are manifested as
SqlDataAdapter and OledbDataAdapter. The
DataAdapter is intended for use with DataSet and can
9

retrieve data from the data source. The DataSet can


contain multiple DataTables disconnected from the
database. The data in the DataSet can be manipulate –
changed, deleted , or added to without an active connection
to the database. The DataAdapter class has four
command objects : SelectCommand , InsertCommand ,
UpdateCommand , and DeleteCommand. The
SelectCommand is used for retrieving data from database,
and other three methods are used for reconciling data
changes in the DataSet.

For Example:
SqlDataAdapter da = new SqlDataAdapter( “Select
* from Table1 “ , con ) ;

DataSet: The dataset is a collection of


DataTables. The DataSet similar to an array of
disconnected RecordSet object. When a connection is
established with the database, the data adapter creates a
DataSet or DataTable and stores data in it. After the data
is retrieved and stored in the DataSet, connection with the
database is closed. The DataSet is present as a DataSet
class in the “System.Data” namespce.

The general Syntax to creating of DataSet is:

DataSet ds = new DataSet();

Example of DataSet and DataAdapter


public void display( )
{
SqlCommand cmd = new SqlCommand("Select * from stud_info", con);
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
10

DataSet ds = new DataSet();


da.Fill(ds, "table1");

foreach (DataRow dr in ds.Tables["table1"].Rows)


{
Console.Write(dr[0] + "\t"+dr[1] + "\t"+dr[2] + "\t"+dr[3] + "\t"+dr[4] + "\t");
}
Console.ReadLine();
“OR”
For ( int I = 0 ;I < ds.Tables[“table1”].rows.Count – 1 ; i + +)
{
Console.Write(ds.Tables["table1"].Rows[i][0]) +”\t “ ) ;
Console.Write(ds.Tables["table1"].Rows[i][1]) +”\t “ ) ;
Console.Write(ds.Tables["table1"].Rows[i][2]) +”\t “ ) ;
Console.Write(ds.Tables["table1"].Rows[i][3]) +”\t “ ) ;
Console.Write(ds.Tables["table1"].Rows[i][4]) +”\n “ ) ;
}

The DataTable class :


A DataTable stores data in a similar form to a database
table. It is a collection of DataRows, DataColumns and
Constraints. The DataTable class is a central class in
the ADO.NET architecture; it can be used independently,
and in DataSet objects. The Columns collection
combined with the Constraints collection defines the
DataTable schema, while the Rows collection contains
the data.

Creating DataTable

DataTable dt1 = new DataTable ( ) ;


DataTable dt2 = new DataTable (“virtual_table_name”);

Adding DataTable into DataSet

ds.Tables.Add(dt1);
11

ds.Tables.Add(dt2);

Here ds is object of DataSet and dt1,dt2 is Object of


DataTable.

DataColumn : A DataColumn defines the column name and


its data type and any primary key or incremental numbering
information. We can create a new DataColumn using the
DataColumn constructor or by invoking the Add() method of
the DataTable . Columns collection property.

Creating DataColumn
DataColumn col1 = new DataColumn( );
DataColumn col2 = new DataColumn( String Column_name );
DataColumn col3= new DataColumn(String Column_name , Type
DataType);
DataColumn col4 = new DataColumn(String Column_name ,
Type
DataType , String expression ) ;

Example :

DataColumn dc1 = new DataColumn ( ) ;


DataColumn dc2= new DataColumn (“Roll “) ;
DataColumn dc3 = new DataColumn ( “Price” , Type.GetType( “ System.Int32
“) ;
DataColumn dc4 = new DataColumn ( “Total” , Type.GetType( “System.Int32”),
“Sum(Price)”);

Adding DataColumn into DataTable

dt.Columns.Add( );
dt.Columns.Add( dc2 );
dt.Columns.Add(“Name”);
dt.Columns.Add(" Price ", Type.GetType("System.Int32"));
dt.Columns.Add("Total", Type.GetType("System.Int32") ,
“Sum(Price)”);

Note :  When we Create and add a new DataColumn to the


DataColumnCollection, the DataColumn is given a default name
12

("Column1", "Column2", etc.). Adds the specified DataColumn to the


DataColumnCollection. dt.Columns.Add ("Total", Type.GetType
(“System.Int32"), "Sum(Price)"); Creates and adds a DataColumn with
the specified name, data type and Expression property. The expression
can be used to filter rows, calculate the values in a column, or create an
aggregate column.

DataRow
The DataRow object contains the data in the DataTable. Each DataRow
has one item per DataColumn in the Columns. It is similar to the Row
collection of the database.

Creating and Adding a new DataRow in the DataTable

DataRow dr ; DataRow dr ;
dr = dt.NewRow( ); dr = dt.NewRow( ) ;
dr[0] = “ 101 ”; dr[“Roll”] = “101” ;
dr[1] = “Ranjit”; “ OR ” dr[“Name”] = “Ranjit” ;
dr[2] = “MCA” ; dr[“ Class “] = “MCA” ;
dt.Rows.Add( dr); dt.Rows.Add( dr ) ;

“ OR “

dt.Rows.Add(new Object[] {“101”,"Ranjit","MCA"});

(iii) Constraints Collection


The Constraints collection is an instance of the ConstraintCollection class, and is a container for zero or
more ForeignKeyConstraint objects and UniqueConstraint objects. The ForeignKeyConstraint object
defines the action to be taken on a column in a primary key / foreign key relationship when a row is updated
or deleted. The UniqueConstraint is used to force all values in a column to be unique.

Creating PrimaryKey Column in a DataTable


DataTable dt = new DataTable("Student");
dt.Columns.Add("Roll");
dt.Columns.Add("Class");
dt.Columns.Add("Name");
dt.Columns.Add("Dist");

DataColumn[] pk = new DataColumn[2];


pk[0] = dt.Columns["Roll"];
13

pk[1] = dt.Columns["Class"];
dt.PrimaryKey = pk;

Creating AutoIncrement Column in DataTable :

dt.Columns["Roll"].AutoIncrement = true;
dt.Columns["Roll"].AutoIncrementStep = 1;
dt.Columns["Roll"].AutoIncrementSeed = 100;
dt.Columns["Roll"].ReadOnly = true;

Note: The DataColumn class also provides properties for definng a column as a ReadOnly ,
AutoIncrement column , AutoIncrementStep with the numbering starting from i.e. AutoIncrementSeed.

Creating ForeignKeyConstraint in the DataSet between DataTables


We can create a relationship between two tables in a DataSet by invoking the
DataSet.Relations.Add ( ) method. There are seven overloaded Add ( ) methods they are:-

(a) DataSet.Relations.Add( DataRelation ) ;

eg:

DataRelation R1 = new DataRelation ( “emp_to_dist”, ds.Tables[“District”].Columns[“Dist”] ,


ds.Tables[“Employee”].Columns[“Dist”] ) ;

ds.Relations.Add ( R1) ;

(b) DataSet.Relations.Add( parent_column_name , child_column_name ) ;

e.g :

ds.Relations.Add ( ds.Tables[" District "].Columns [ " Dist "] , ds.Tables[ "


Employee " ].Columns[ " Dist " ] ) ;

(c) DataSet.Relations.Add( parent_column_name[ ] , child_column_name [ ] ) ;

(d) DataSet.Relations.Add( String relation_name , parent_column_name ,


child_column_name ) ;

eg:
parent_column = ds.Tables[“District”].Columns[“Dist”] ;
child_column = ds.Tables[“Employee”].Columns[“Dist”] ;
ds.Relations.Add(“emp_to_dist” , parent_column , child_column ) ;

(e) DataSet.Relations.Add( String relation_name , parent_column_name [ ] ,


child_column_name [ ] ) ;
14

(f) DataSet.Relations.Add( String relation_name , parent_column_name ,


child_column_name , boolean) ;

(g) DataSet.Relations.Add( String relation_name , parent_column_name[ ] ,


child_column_name[ ] , boolean) ;

Note: Here boolean argument indicates whether or not to create constraints.

Accessing Perticular Cell in the DataTable with DataSet

DataSet

Student DataTable

Roll Name Course Phone


101 Ranjit MCA 686867867
102 Shashi MBA 789797766
103 Braj M Tech 566575757
104 Vijay BCA 678686866

Employee DataTable

Code Name Dist Phone


1001 Ranjit Patna 686867867
1002 Shashi Mokama 789797766
1003 Braj Siwan 566575757
1004 Vijay Jahanabad 668666667

MessageBox.Show(ds.Tables[0].Rows[2].ItemArray[2].ToString());  M Tech
MessageBox.Show(ds.Tables[1].Rows[2][2].ToString());  Siwan
MessageBox.Show(ds.Tables[1].Rows[0].ItemArray[1].ToString());  Ranjit
MessageBox.Show(ds.Tables[1].Rows[0][2].ToString());  Patna
MessageBox.Show(ds.Tables[1].Rows[3].ItemArray[2].ToString());  Jahanabad
MessageBox.Show(ds.Tables[1].Rows[0][2].ToString());  Patna

DataGridView Control
DataGridView control is the main data display control for displaying and
editing tabular data in windows applications. The DataGridView Control has
many properties, methods, and events for customizing its appearance and
behavior. When we have to display tabular data either with small number of
15

records or with large number of records, DataGridView control is the best


choice for both cases.

Some important properties : 

Property
1. AllowUserToAddRows
2. AllowUserToDeleteRows
3. AllowUserToResizeColumns
4. AllowUserToResizeRows
5. AutoGenerateColumns
6. BackgroundColor
7. CurrentCell
8. DataSource
9. DataMember
10. AutoSizeColumnsMode
11. Columns
12. DefaultCellStyle
13. MultiSelect
14. RowHeaderVisible
15. RowDefaultCellStyle
16. RowTemplate
17. ScrollBars

Some important Methods of DataGridView Control : 

Methods Description
GetCellCount It gets the number of cells that satisfy
the provided filter.
HitTest It returns the location information such
as rows and columns index given x and y
co-ordinates

Some important Events of DataGridView Control : 

Events Description
CellClick Occurs when any part of a cell is clicked
CellContentDoubleClick Occurs when the user double click on a cell
contents.
CellEnter Occurs when the currents cell recieves input
focus.
16

CellMouseClick Occurs when the user clicks any where on a


cell with the mouse.
CellEndEdit Occurs when edit mode stops for the
currently selected cell.
Scroll Occurs when the grid scrolls horizontally or
vertically.

DataBinding:  The Process of linking a control to a datasource is called


databinding. DataBinding is the ability to bind some elements of a datasource
with the controls of an application. There are two types of databindings they are
:----

(i) Simple DataBinding :  Simple databinding is the process of


binding a control to a single value in a DataSet. It means, A control that
supports simple data bindings typically displays only a single value at once ,
such as TextBox, Label , RadioButton,CheckBox etc.

(ii) Complex DataBinding : Complex databinding is the ability


to bind a control to more than one data element and more than one records in a
database.Some of the controls which support complex data binding are
DataGridView, ComboBox, ListBox, and CheckListBox.

DataBinding With DataGridView Control : There are several


types of databinding with DataGridView control:---

grd1.DataSource = dt;

“OR”

grd1.DataSource = ds.Tables[0] ;

“OR”

grd1.DataSource = ds ;
grd1.DataMembers = ds.Tables[0].TableName;

“OR”

grd1.DataSource = ds ;
grd1.DataMember = “student” ;

“OR”

grd1.DataBindings.Add( “DataSource” , ds , “Student”) ;

“OR”
17

grd1.DataBindings.Add("DataSource",ds,ds.Tables[0].TableNam
e);

Example of DataSet , DataTable , DaraColumn , DataRow and DataGridView


with Complex DataBinding :
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable("stud");
dt.Columns.Add("Roll");
dt.Columns.Add("Name");
dt.Columns.Add("Phone");
DataRow rw = dt.NewRow();
rw[0] = "101";
rw[1] = "Ranjit";
rw[2] = "78678";
dt.Rows.Add(rw);
dt.NewRow();
dt.Rows.Add(new Object[] { "102", "Vijay", "678634" });
dt.NewRow();
dt.Rows.Add(new Object[] { "103", "Shashi", "2746078"});
dt.NewRow();
dt.Rows.Add(new Object[] { "104", "Braj", "257398" });
DataSet ds = new DataSet();
ds.Tables.Add(dt);
dataGridView1.DataBindings.Add("DataSource", ds, ds.Tables[0].TableName);
}
Example of DataBinding with DataGridView using DataAdapter,
DataSet, SqlCommand and SqlDataReader

using System;
18

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication10
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=desktop; database=student; integrated
security=sspi");
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("Select * from marks_details", con);
if (ds.Tables.Contains("marks") == true)
{
ds.Tables.Remove("marks");
}
da.Fill(ds, "marks");
grd1.DataSource = ds.Tables["marks"];
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Select * from stud", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (ds.Tables.Contains("details") == true)
{
ds.Tables.Remove("details");
}
ds.Load(dr, LoadOption.Upsert, "details");
grd1.DataSource = ds.Tables["details"];
con.Close();
}
}
}
Example of DataBinding with TextBox
If we want to add a TextBox control to a form and bind it to a column of a
table in a DataSet, the control is going to communicate with the
BindingContext object for this . The BindingContext object is going to
talk to the specific CurrencyManager object for the data the TextBox
control is binding.
19

Every Windows Form has a BindingContext object keeping


track of all the CurrencyManager objects on the windows Form. The
CurrencyManager keeps track of the position in the datasource. When
we bind a dataobject to a control , a CurrencyManager object is
automatically assigned. If we bind several controls to same data source ,
they share the same CurrencyManager.

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication9
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=desktop; database=student; integrated
security=sspi");
SqlDataAdapter da;
DataSet ds = new DataSet();
CurrencyManager cm;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
da = new SqlDataAdapter("Select * from marks_details", con);
da.Fill(ds,"marks");
textBox1.DataBindings.Add("Text", ds, "marks.stud_code");
textBox2.DataBindings.Add("Text", ds, "marks.subject");
textBox3.DataBindings.Add("Text", ds, "marks.marks");
button1.Enabled = false;
button2.Enabled = false;
20

cm = (CurrencyManager)BindingContext[ds, ds.Tables[0].TableName];
vsb.Maximum = cm.Count - 1;
vsb.Minimum = 0;
}
private void btn_first_Click(object sender, EventArgs e)
{
//BindingContext[ds, "marks"].Position = 0;
cm.Position = 0;
vsb.Value = cm.Position;
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button4.Enabled = true;
}
private void btn_next_Click(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = true;
cm.Position ++;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Position + 1;
vsb.Value = BindingContext[ds, "marks"].Position;
if (BindingContext[ds, "marks"].Count-1 == BindingContext[ds, "marks"].Position)
{
button3.Enabled = false;
button4.Enabled = false;
}
}
private void btn_prev_Click(object sender, EventArgs e)
{
button3.Enabled = true;
button4.Enabled = true;
cm.Position --;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Position - 1;
vsb.Value = BindingContext[ds, "marks"].Position;
if (BindingContext[ds, "marks"].Position==0)
{
button1.Enabled = false;
button2.Enabled = false;
}
}
private void btn_last_Click(object sender, EventArgs e)
{
cm.Position = cm.Count - 1;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Count - 1;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
button4.Enabled = false;
21

vsb.Value = cm.Position;
}
private void vsb_Scroll(object sender, ScrollEventArgs e)
{
cm.Position = vsb.Value;
//BindingContext[ds, ds.Tables[0].TableName].Position = vsb.Value;
if (vsb.Value == 0)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button4.Enabled = true;
}
if (vsb.Value == cm.Count-1)
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
button4.Enabled = false;
}
if (vsb.Value > 0 && vsb.Value <cm.Count- 1)
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
}
}
}
}

Use of CommandBuilder with DataGridView


SqlCommandBuilder is a class in ado.net that provides the feature of
reflecting the changes made to a dataset or datatable. The
sqlcommandbuilder object automatically generates the values contained
within the sqldataadapter’s insert command, update command and
delete command based on the select command.
22

public partial class Form1 : Form


{
SqlConnection con = new SqlConnection("Server=desktop; database=student; integrated
security=sspi");
SqlDataAdapter da;
DataTable dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * from marks_details", con);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(dt);
grd1.DataSource = dt;
}
private void btn_update_Click(object sender, EventArgs e)
{
da.Update(dt);
dt.AcceptChanges();
grd1.DataSource = dt;
}
}

How To Insert Image into DataBase and display its into


DataGridView in c#.net
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
23

using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace WindowsApplication2
{
public partial class Form1 : Form
{
static String path = "";
SqlConnection con = new SqlConnection("Server=desktop; database=student;
Integrated Security=sspi");
public Form1()
{
InitializeComponent();
}
private void form1_Load(Object sender , EventArgs e)
{
Bitmap b = new Bitmap(200,200);
b.Save("c:\\pict1.jpg");
Path="c:\\pict1.jpg";

}
private void btn_display_Click(object sender, EventArgs e)
{

dataGridView1.RowTemplate.Height = 150;
dataGridView1.AutoSizeColumnsMode= DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.ReadOnly = true;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}

private void btn_Insert_Click(object sender, EventArgs e)


{
byte[] data = File.ReadAllBytes(path);

SqlCommand cmd = new SqlCommand("Insert into stud_info


values(@roll,@name,@pict)", con);
con.Open();
cmd.Parameters.AddWithValue("@roll", txt_roll.Text);
cmd.Parameters.AddWithValue("@name", txt_nm.Text);
cmd.Parameters.AddWithValue("@name", data);

cmd.ExecuteNonQuery();
24

MessageBox.Show("Inserted");
con.Close();
}

private void pictureBox1_Click(object sender, EventArgs e)


{
openFileDialog1.Filter = "Image File(*.BMP;*.JPG;*.GIF)|*.BMP ;*.JPG;*.GIF";
openFileDialog1.ShowDialog();
path = openFileDialog1.FileName;
pictureBox1.ImageLocation=path;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void txt_roll_TextChanged(object sender, EventArgs e)
{
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from stud1 where roll='" + txt_roll.Text
+ "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
if (File.Exists("c:\\img.jpg"))
{
File.Delete("c:\\img.jpg");
}
if (dt.Rows.Count > 0)
{
Txt_nm.Text = dt.Rows[0]["name"].ToString();
byte[] data = (byte[])dt.Rows[0]["image"];
File.WriteAllBytes("c:\\img.jpg", data);
pictureBox1.ImageLocation = "c:\\img.jpg";
}
else
{
Txt_nm.Text = "";
pictureBox1.ImageLocation = "";
}
}
catch
{
}
}
}
}

Output will be as :----


25

How To save/Retrieve Image and Audio/Video Files in the Sqlserver


database :

(i) First of all we have to drag and drop two textbox,two label,two
button,one picturebox and two “openfiledialog” control on the form.

(ii) Right click on the any tab of “toolbox” and select “choose Items”
menu as :--
26

(iii) Then we find a new window for adding the new control in toolbox as:--

(iv) Select the “Windows Media Player” and click on the “OK” button.

(v) Drag and drop “Windows Media Player” control from “toolbox” on the Form as :--

(vi) Create a table “stud1” in sqlserver database as :

(vii) Associate the following namespace :--


27

using System.Data.SqlClient;
using System.IO;

(viii) Create some objects in the global section as :--

SqlConnection con = new SqlConnection("server=india; database=sushant; integrated


security=sspi");

String img_path = "",snd_path="";

(ix) Double click on the picturebox and edit the code as :--

private void pictureBox1_Click(object sender, EventArgs e)


{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
img_path = openFileDialog1.FileName;
pictureBox1.ImageLocation = img_path;
}
}

(x) Double click on the “Select Sound file” button and edit the code as :

private void button3_Click(object sender, EventArgs e)


{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
snd_path = openFileDialog2.FileName;
axWindowsMediaPlayer1.URL = snd_path;
}
}
(xi) Double click on the save button and edit the code as :--

private void button1_Click(object sender, EventArgs e)


{
byte[] data = File.ReadAllBytes(img_path);
byte[] snd = File.ReadAllBytes(snd_path);
String ext = snd_path.Split('.')[1];

SqlCommand cmd = new SqlCommand("insert into stud1(roll,


name,image,sound,sound_ext) values(@roll,@nm,@img,@sound,@ext)", con);

cmd.Parameters.AddWithValue("@roll",textBox1.Text);
cmd.Parameters.AddWithValue("@nm", textBox2.Text);
cmd.Parameters.AddWithValue("@img", data);
cmd.Parameters.AddWithValue("@sound", snd);
cmd.Parameters.AddWithValue("@ext", ext);

con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("saved");
}

(xii) Double click on the form and edit the code as :


28

private void Form1_Load(object sender, EventArgs e)


{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.BorderStyle = BorderStyle.FixedSingle;
if (Directory.Exists("c:\\sound")==false)
{
Directory.CreateDirectory("c:\\sound");
}
}

(xiii) Double click on the roll textbox and edit the code as :

private void textBox1_TextChanged(object sender, EventArgs e)


{
try
{
SqlDataAdapter da = new SqlDataAdapter("select * from stud1 where roll='" +
textBox1.Text + "'", con);

DataTable dt = new DataTable();


da.Fill(dt);
axWindowsMediaPlayer1.URL = "";
String[] files = Directory.GetFiles("c:\\sound", "*.*");
foreach(String file in files)
{
File.Delete(file);
}
if (dt.Rows.Count > 0)
{
textBox2.Text = dt.Rows[0]["name"].ToString();
byte[] img = (byte[])dt.Rows[0]["image"];
byte[] snd = (byte[])dt.Rows[0]["sound"];
String ext = dt.Rows[0]["sound_ext"].ToString();

File.WriteAllBytes("c:\\sound\\img.jpg", img);
pictureBox1.ImageLocation = "c:\\img.jpg";

File.WriteAllBytes("c:\\sound\\snd1."+ext, snd);
axWindowsMediaPlayer1.URL = "c:\\sound\\snd1."+ext;
}
else
{
textBox2.Text = "";
pictureBox1.ImageLocation = "";
}
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
}

(xiv) Press F5 key to execute the program.

Insert / update / delete and display the record using


disconnected model :à
29

(i) Design the Form As:

(ii) Double click on the roll TextBox and edit the code as :

private void txt_roll_TextChanged(object sender, EventArgs e)


{
SqlDataAdapter da=new SqlDataAdapter("select * from stud_info where roll='" +
txt_roll.Text + "'", con);

DataTable dt = new DataTable();


da.Fill(dt);
if (dt.Rows.Count > 0)
{
txt_nm.Text = dt.Rows[0][1].ToString();
txt_add.Text = dt.Rows[0][2].ToString();
txt_ph.Text = dt.Rows[0][3].ToString();
btn_save.Enabled = false;
btn_update.Enabled = btn_del.Enabled = true;
}
else
{
txt_nm.Text = txt_add.Text = txt_ph.Text = "";
btn_save.Enabled = true;
btn_update.Enabled = btn_del.Enabled = false;
}
}

(iii) Double click on the Save button and edit the code as :

private void btn_save_Click(object sender, EventArgs e)


{
SqlDataAdapter da=new SqlDataAdapter("select * from stud_info where roll='" +
txt_roll.Text + "'", con);

DataTable dt = new DataTable();


new SqlCommandBuilder(da);
da.Fill(dt);
dt.Rows.Add(new Object[] { txt_roll.Text, txt_nm.Text, txt_add.Text,
txt_ph.Text });
da.Update(dt);
dt.AcceptChanges();
MessageBox.Show("Successfully saved");
30

txt_roll.Clear();
txt_roll.Focus();
}

(iv) Double click on the update button and edit the code as :
private void btn_update_Click(object sender, EventArgs e)
{
SqlDataAdapter da=new SqlDataAdapter("select * from stud_info where roll='" +
txt_roll.Text + "'", con);

DataTable dt = new DataTable();


new SqlCommandBuilder(da);
da.Fill(dt);
DataColumn[] dc = new DataColumn[1];
dc[0] = dt.Columns[0];
dt.PrimaryKey = dc;

DataRow row = dt.Rows.Find(txt_roll.Text);


row[0] = txt_roll.Text;
row[1] = txt_nm.Text;
row[2] = txt_add.Text;
row[3] = txt_ph.Text;

//"OR"

dt.Rows[0][0] = txt_roll.Text;
dt.Rows[0][1] = txt_nm.Text;
dt.Rows[0][2] = txt_add.Text;
dt.Rows[0][3] = txt_ph.Text;

da.Update(dt);
dt.AcceptChanges();
MessageBox.Show("Successfully updated");
}

(v) Double click on the delete button and edit the code as :

private void btn_del_Click(object sender, EventArgs e)


{
SqlDataAdapter da=new SqlDataAdapter("select * from stud_info where roll='" +
txt_roll.Text + "'", con);

DataTable dt = new DataTable();


new SqlCommandBuilder(da);
da.Fill(dt);
DataColumn[] dc = new DataColumn[1];
dc[0] = dt.Columns[0];
dt.PrimaryKey = dc;
DataRow row = dt.Rows.Find(txt_roll.Text);
row.Delete();
da.Update(dt);
MessageBox.Show("Successfully deleted");
txt_roll.Clear();
}

Note : The “Roll” column must be set as the primary key in database table.
31

Using a Command with a Stored Procedure


We can use the command objects to execute stored procedures on the database. The
command classes have a CommandType property that takes one of three possible
CommandType enumeration values, Text, StoredProcedure, or TableDirect. By
default, the CommandType property is set to CommandType.Text. By constructing
the command object with a stored procedure name, or setting the CommandText to a
stored procedure name, we can execute that stored procedure on the database.

Note: The TableDirect values use only into MS Access database for display the record..

Example of Stored Procedure for displaying record into DataGridView


Step I :- First of all, we have to create a procedure into sqlserver database as:----

CREATE PROCEDURE DISPLAY_RECORD AS


SELECT * FROM STUD_INFO

Note :If we want to delete the procedure then we have to write as:---

DROP PROCEDURE DISPLAY_RECORD

Step II :- we have to write the code into c#.net editor as :----

using System;
using System.Data.SqlClient;
namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india;database=student;integrated
security=sspi");

private void button1_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand("display_record", con);
cmd.CommandType = CommandType.StoredProcedure;
// If we don’t pass any parameter then above line is optional.
SqlDataAdapter da =new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
Da.Fill(dt)
dataGridView1.DataSource = dt;
32

}
}
}

Example of Parameterized Stored Procedures

CREATE PROCEDURE DISPLAY_RECORD (@STUD_NAME VARCHAR(50))


AS
SELECT * FROM STUD_INFO WHERE NAME like @STUD_NAME

using System;
using System.Data.SqlClient;

namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit;
database=student;integrated security=sspi");
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand("display_record", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@stud_name", textBox1.Text);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
Da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
33

Insereting Data into Sql Table Using Stored Procedures

CREATE PROCEDURE INSERT_RECORD (@STUD_ROLL VARCHAR(20),


@STUD_NAME VARCHAR(50), @STUD_PHONE VARCHAR(20)) AS
INSERT INTO STUD_INFO (ROLL,NAME,CONTACT)
VALUES(@STUD_ROLL,@STUD_NAME,@STUD_PHONE)

using System;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit;
database=student;integrated security=sspi");
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand("Insert_record", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@stud_roll", textBox1.Text);
cmd.Parameters.AddWithValue("@stud_name", textBox2.Text);
cmd.Parameters.AddWithValue("@stud_phone", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully Record Saved");
con.Close();
}
}
34

Fill Record into DataGridView Manually


Step 1 : First of All, we have to add the the column of DataGridView by
selecting Column property .

Step 2 : Write the code as:---

using System;
using System.Data.SqlClient;

namespace WindowsApplication4
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=india\\ranjit; database=student;integrated security=sspi");

private void button1_Click(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand("display_record", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
int i = 0;
while (dr.Read())
{
dataGridView1.Rows.Add();
dataGridView1[0, i].Value = dr[0];
dataGridView1[1, i].Value = dr[1];
i++;
}
con.Close();

}
}
}
35

DataBinding With ComboBox:-


using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication6
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=india\\ranjit; database=student; integrated
security=sspi");
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("selected index = "+comboBox1.SelectedIndex.ToString());
MessageBox.Show("Selected value= "+comboBox1.SelectedValue.ToString());
MessageBox.Show("Selected Item= "+comboBox1.SelectedItem.ToString());
MessageBox.Show("Selected text= "+comboBox1.SelectedText.ToString());
}

private void Form1_Load(object sender, EventArgs e)


{
SqlCommand cmd = new SqlCommand("Select * from stud_info", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
ds.Load(dr, LoadOption.Upsert, "stud");
comboBox1.DataSource = ds;
comboBox1.DisplayMember = "stud.roll";
comboBox1.ValueMember = "stud.name";
con.Close();

}
}
}
36

DataBinding with ListBox:


private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox.SelectedObjectCollection col = listBox1.SelectedItems;
label1.Text = "";
foreach (DataRowView rw in col)
{
label1.Text = label1.Text + rw.Row[0] + " " + rw.Row[1] + "\n";
}
}

private void Form1_Load(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("select * from dist_table", con);
DataTable dt = new DataTable();
da.Fill(dt);
listBox1.DisplayMember = "dist_name";
listBox1.ValueMember = "dist_code";
listBox1.DataSource = dt;
}

Output Will be as :

Handling With DataGridView Control:


37

using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;

namespace WindowsApplication7
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit; database=student; integrated security=sspi");
Font f20 = new Font("", 20, FontStyle.Bold);
Font f11 = new Font("",11, FontStyle.Regular);
int row, col;
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.RowTemplate.Height = 30;
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
DataSet ds = new DataSet();
da.Fill(ds, "stud");
dataGridView1.DataSource = ds.Tables[0];
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
Random rand = new Random();
int r=rand.Next(1, 255);
int g = rand.Next(1, 255);
int b = rand.Next(1, 255);
Thread.Sleep(50);
col.DefaultCellStyle.BackColor = Color.FromArgb(r, g, b);
}
}
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex>=0)
{
row = e.RowIndex;
col = e.ColumnIndex;
dataGridView1[e.ColumnIndex, e.RowIndex].Style.Font = f20;
}
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[col,row].Style.Font = f11;
}
}
}
38

Creating XML File Using DataSet/DataTable:


(i) Design a form with three buttons as below:---

(ii) After designing we have to write the code as:----

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication11
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit; database=student; integrated
security=sspi");

private void button1_Click(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
DataSet ds = new DataSet(); “or” DataTable dt=new DataTable(“stud”);
da.Fill(ds, "stud"); “or” da.Fill(dt);
ds.WriteXml("c:\\file1.xml"); “or” dt.WriteXml(“c:\\file1.xml”);
}
39

private void button2_Click(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
DataSet ds = new DataSet();
da.Fill(ds, "stud");
ds.WriteXmlSchema("c:\\file2.xml");
}

private void button3_Click(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
DataSet ds = new DataSet();
da.Fill(ds, "stud");
ds.WriteXml("c:\\file3.xml", XmlWriteMode.WriteSchema);
}

}
}

Fill Data In DataGridView Control from XML File:


(i) First of all we have to design a form with one DataGridView and one Button.

(ii) Then have to write the code on Click event of button1 as :----

private void button1_Click(object sender, EventArgs e)


{
DataTable dt = new DataTable();
dt.ReadXml("c:\\myfile3.xml");
dataGridView1.DataSource = dt;
}

Note 1 : Here Connection is not necessary for displaying data from xml file.

Note 2: If We write dt.ReadXmlSchema("c:\\myfile3.xml"); then only column header displaying in


the DataGridView control

Accessing Data Using Server Control


Step 1. : Create a new windows application.

Step 2 :  If server explorer window has not available then select menu view  server
explorer or by pressing Ctrl + W , S.

Step 3 :  Right click on Data Connection option in the server explorer. Window.
40

Step 4 :  Select Add Connection item. Then display the window as below

Step 5 : Double Click on Microsoft SQL Server or click on Continue Button then display the
as :----
41

Step 6 :  Type Server Name of SQL Server and then select database.

Step 7 :  Click on Test Connection Button.

Step 8 : If Test Connection is Succeeded then Click On OK Button.

Displaying Data In a DataGridView

(i) Add a DataGridView Control on Form1 from the toolbox.

(ii) Click on Right Top Corner on Triangle Symbol of the DataGridView control

(iv) Expand the Choose Data Source Combo box then find the window as :----

(iv) Click on Add Project Data Source then display the window as:----
42

(v) Select DataBase Icon and then Click on Next Button.

(vi) Choose or select data connection name in the combo box and click on Next Button.

(vii) Again Click on Next Button.

(viii) Select Tables and then click on Finish Button

Transaction: ALL or Nothing ---- this is the main feature of a transaction. When writing a
few records then either all are written or every thing will be undone. If there is just one failure
when writing one records, all the other things that are done within the transaction are rollback.
Transactions are commonly used with database, but we can also perform
transactions on volatile in memory based objects such as list of objects. With a list that supports
transactions, if an object is added or removed and the transaction fails, the list action is
automatically undone.

Example:

private void button1_Click(object sender, EventArgs e)


{
43

SqlCommand cmd1 = new SqlCommand("insert into stud_info(roll,name,contact)


values(1002,'ranjit','5676567')", con);
SqlCommand cmd2 = new SqlCommand("insert into stud values('1002')", con);
con.Open();
SqlTransaction tx = con.BeginTransaction();
try
{
cmd1.Transaction = tx;
cmd2.Transaction = tx;
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
tx.Commit();
con.Close();
MessageBox.Show("inserted");
}
catch (Exception ex)
{
tx.Rollback();
con.Close();
MessageBox.Show(ex.ToString());
}
}
}
}

Connectivity with Oracle:


using System;
using System.Data;
using System.Data.OleDb;

class OleDbConnectionOracle
{
public static void Main()
{
string connectionString = "provider=MSDAORA;data source=ORCL;user
id=SCOTT;password=TIGER";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);

OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();

myOleDbCommand.CommandText = "SELECT empno, ename, sal FROM emp WHERE empno


= 7369";

myOleDbConnection.Open();

OleDbDataReader myOleDbDataReader = myOleDbCommand.ExecuteReader();

myOleDbDataReader.Read();

Console.WriteLine("myOleDbDataReader[\" empno\"] = " + myOleDbDataReader["empno"]);


Console.WriteLine("myOleDbDataReader[\" ename\"] = " + myOleDbDataReader["ename"]);
44

Console.WriteLine("myOleDbDataReader[\" sal\"] = " + myOleDbDataReader["sal"]);

myOleDbDataReader.Close();
myOleDbConnection.Close();
}
}

Qn. Develop a simple project that should be following operation in given


diagram:-----

Ans:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
45

public partial class Form1 : Form


{
SqlConnection con = new SqlConnection("server=ranjit\\ranjit;
database=temp; integrated security=sspi");

SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable dt;
CurrencyManager cm;

private void Form1_Load(object sender, EventArgs e)


{

databinding();
}

private void button4_Click(object sender, EventArgs e)


{
cm.Position = cm.Count - 1;
}

private void btn_first_Click(object sender, EventArgs e)


{
cm.Position = 0;
}

private void btn_prev_Click(object sender, EventArgs e)


{
cm.Position--;
}
private void btn_next_Click(object sender, EventArgs e)
{
cm.Position++;
}
private void btn_add_new_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox1.Focus();
}
private void btn_save_Click(object sender, EventArgs e)
{

dt.NewRow();
dt.Rows.Add(textBox1.Text, textBox2.Text);
da.Update(dt);
dt.AcceptChanges();
cm.Position++;
MessageBox.Show("Record saved");
}

private void btn_update_Click(object sender, EventArgs e)


{
cm.Position++;
da.Update(dt);
dt.AcceptChanges();
MessageBox.Show("Record Updated");
}
private void btn_delete_Click(object sender, EventArgs e)
46

{
con.Open();
SqlCommand cmd = new SqlCommand("Delete from stud where roll='" +
textBox1.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
databinding();
MessageBox.Show("Record Deleted");
}
public void databinding()
{
da = new SqlDataAdapter("Select * from stud", con);
dt = new DataTable("stud");
builder = new SqlCommandBuilder(da);
da.Fill(dt);
textBox1.DataBindings.Clear();
textBox2.DataBindings.Clear();

textBox1.DataBindings.Add("text", dt, "roll");


textBox2.DataBindings.Add("text", dt, "name");
cm = (CurrencyManager)this.BindingContext[dt];
}
}
}

Creating Report using CrystalReport :


(i) First of all we have to open a new windows Application.
(ii) Drag and drop one Button and one CrystalReportViewer on the form as :--

(iii) Double click on the button and edit the code as :--

private void button1_Click(object sender, EventArgs e)


{
SqlConnection con = new SqlConnection("server=india; database=ranjit;
integrated security=sspi");
SqlDataAdapter da = new SqlDataAdapter("select * from stud_info", con);
DataTable dt = new DataTable("stud");
da.Fill(dt);
dt.WriteXml("c:\\myxml.xml", XmlWriteMode.WriteSchema);
}
47

(iv) After editing the above code we have to execute the program and click on the
button for creating the “xml” file.
(v) Select the menu “projectAdd windows FormCrystal ReportAddOkCreate
new Connection  Database Files  Select our xml file in c: drive  click on
the button  finish “.
(vi) Expand the “Database fields” and Tables in “Field Explorer” window.
(vii) Drag and drop All Columns from “Field Explorer” window in the “Details
section” of the Crystal Report page as our requirements. For Example…

(viii) After Designing the Crystal Report Page Again we have to double click on the button and
append the code as :

private void button1_Click(object sender, EventArgs e)


{
SqlConnection con = new SqlConnection("server=india; database=ranjit; integrated security=sspi");
SqlDataAdapter da = new SqlDataAdapter("select * from stud_info", con);
DataTable dt = new DataTable("stud");
da.Fill(dt);
dt.WriteXml("c:\\myxml.xml", XmlWriteMode.WriteSchema);

CrystalReport1 doc = new CrystalReport1();


doc.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.
PortableDocFormat , "c:\\report.pdf");
crystalReportViewer1.ReportSource = doc;
doc.Refresh();
}

(ix) Press “F5” key to execute the program.

Creating RDLC(Report Definition Language


Client-side) Report in VS 2012:
(i) Open a new windows application as Form1.
(ii) Drag and drop one “ReportViewer” control from “Reporting tab” in toolbox
named as “reportViewer1“.
(iii) Click on triangle symbol(Right-Top corner) of “reportviewer1” control then
click on “Design a new Report” link then we find a new window.
(iv) Select “database” and click on next button.
48

(v) Select “dataset” then click on next button.


(vi) Click on “New Connection” button then we find a new window for creating a
new connection and dataset.
(vii) Type server name of sqlserver and select our database name in the
displaying window and then click on “Test Connection” button.
(viii) Now Click on “OK” button then “Next” button again “Next” button.
(ix) Now expand the “Table” and then select our created table of database and
then click on “Finish” button.
(x) Click on “Next” button then we find a “Report Wizard” window with four
Listbox for arranging the column.
(xi) Now drag and drop our required column name in the “Values” listbox and
then click on the “Next” button again click on “Next” button then click on
“Finish” button then we find “Report1.rdlc” file.
(xii) Again click on triangle symbol of “reportViewer1” control of “Form1” and
then select “report1.rdlc” file in the “combobox” and then click on the
“Rebind Data Sources” link.
(xiii) We can also add Page Header and Page Footer By “Right click” in the
“Report1.rdlc” file.
(xiv) Press F5 key for execute the program.

Creating Dynamic Report in RDLC :

(i) Open a new windows application in vs.net 2012.


(ii) Drag and drop one Label, one Button, one TextBox and one ReportViewer
control on the form1 as:-

(iii) Double click on the button and edit the code as :-

private void button1_Click(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("select * from
stud_info where name like '"+textBox1.Text+"%'", con);
DataTable dt = new DataTable("stud1");
da.Fill(dt);
dt.WriteXmlSchema("c:\\Data.xsd");
}
49

(iv) Press F5 key then click on the Button for creating the “.xsd” file in “C:” drive.
(v) Now add “Data.xsd” file in our project by Right click on the project in Solution Explorer,
then select “Add  Existing Item” and then browse for “Data.xsd” file in “C:” drive and
add it to the project.
(vi) Now select the menu “ProjectAdd Windows
FormReportingReportAdd” then we find a “Report1.rdlc” file with
“Report Data” explorer window.
(vii) Right click on the “DataSets” in “Report Data” window then click on the “Add
DataSet” then we find a new window then select DataSource name in the
combobox as “NewDataSet” and click on “OK” button as:-

(viii) Now right click within “Report1.rdlc” file then select “InsertTable” then we
find a table by three columns and one rows.
(ix) Drag and drop our required columns from “Report
DataDataSetsDataSet1” within table as :-

(x) We can also add Page Header, Page Footer and Sets the background,
foreground, Font etc property of our report.
(xi) Now Again double click on the Button in “Form1” and append the code as:

private void button1_Click(object sender, EventArgs e)


{
SqlDataAdapter da = new SqlDataAdapter("select * from stud_info where name like
'"+textBox1.Text+"%'", con);
DataTable dt = new DataTable("stud1");
da.Fill(dt);
dt.WriteXmlSchema("c:\\Data.xsd");

reportViewer1.LocalReport.ReportPath ="c:\\users\\ranjit\\
50

documents\\visual studio 2012\\Projects\\


WindowsFormsApplication5\\WindowsFormsApplication5\\
Report1.rdlc";

reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(new
Microsoft.Reporting.WinForms.
ReportDataSource("DataSet1", dt));
reportViewer1.RefreshReport();
}

(xii) Press F5 Key to execute the program.

The output of above program is :-

Display Records in DataGridView From MsExcel


:
(i) First of all we have to create an Excel file in any drive with some records (For
Example: “c:\myfile1.xlsx”). As:-

(ii) Open Windows Application in C#.net.


(iii) Now Drag and Drop one DataGridView and one Button on the Form.
(iv) Associate the following namespace:-

using System.Data.OleDb;
51

(v) Create the Connection object in the Global section as:-

OleDbConnection con = new


OleDbConnection("provider=microsoft.ace.ol
edb.12.0; data source=c:\\myfile1.xlsx;
extended properties='Excel 12.0;
ReadOnly=False; HDR=yes'");

Note:
(a) HDR=Yes; means it allows the first row of
excel sheet is display in the Heading;

(vi) Double click on the Button and edit the code as :--

private void button1_Click(object sender, EventArgs


e)
{
OleDbDataAdapter da = new
OleDbDataAdapter("select *
from [sheet1$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}

(vii) Press F5 key to execute the program.

The output of above program is :


52

How to Save Record in ExcelSheet using C#.net:


(i) Open a new windows application.
(ii) Design the Form as :-

(iii) Create the connection object in the global section as :--

OleDbConnection con = new


OleDbConnection("provider=microsoft.ace.oledb.12.0;
data
source=c:\\myfile1.xlsx; extended properties='Excel
12.0;
ReadOnly=False; HDR=yes'");

(iv) Double click on the Save Button and edit the code as :--

private void button2_Click(object sender, EventArgs e)


{
OleDbCommand cmd = new OleDbCommand("insert into [sheet1$]
([Roll],[Name],[Address],[Phone]) values('" +
textBox1.Text + "','" + textBox2.Text + "','" +
textBox3.Text + "','" + textBox4.Text + "')",
con);

“OR”
53

OleDbCommand cmd = new OleDbCommand("insert into [sheet1$]


(Roll,Name,Address,Phone) values('" +
textBox1.Text
+ "','" + textBox2.Text + "','" + textBox3.Text
+
"','" + textBox4.Text + "')", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Successfully saved");
}

(v) Execute the above program.

Display List of all databases in sqlserver with


details:

(i) exec sp_databases


(ii) select name from sysdatabases
(iii) select * from sysdatabases
(iv) select name from sysdatabases where dbid>4
(v) select name from sysobjects where type='u' (This
command displays the list of all tables in the current
database.)

Convert Date&Time Format in Sqlserver:Using


convert() function in sqlserver we can change the format of
date and time at display time. In convert function we have to
pass the three parameters, first parameter for size, second
parameter for any column name that stored date&time value
and the third parameter for format code. The format code is
predefined for different date format. Some important code
and its date format type is :--
Note: The getdate() function of sqlserver returns the system date and time.
(i) select convert(varchar(20),getdate(),101) --> mm/dd/yyyy
(ii) select convert(varchar(20),getdate(),1) --> mm/dd/yy
54

(iii) select convert(varchar(20),getdate(),0) --> month/dd/yyyy


hh:mm AM/PM
(iv) select convert(varchar(20),getdate(),100) -->
month/dd/yyyy hh:mm AM/PM
(v) select convert(varchar(20),getdate(),103) --> dd/mm/yyyy
(vi) select convert(varchar(20),getdate(),3) --> dd/mm/yy
(vii) select convert(varchar(20),getdate(),105) --> dd-mm-yyyy
(viii) select convert(varchar(20),getdate(),5) --> dd-mm-yy
(ix) select convert(varchar(20),getdate(),108) --> hh:mm:ss
(x) select convert(varchar(20),getdate(),110) --> mm-dd-yyyy
(xi) select convert(varchar(20),getdate(),10) --> mm-dd-yy
(xii) select convert(varchar(20),getdate(),111) --> yyyy/mm/dd
(xiii) select convert(varchar(20),getdate(),11) --> yy/mm/dd
(xiv) select convert(varchar(20),getdate(),121) --> yyyy/mm/dd
hh:mm:ss
(xv) select roll,name,convert(varchar(20),dob,103) 'Date Of
Birth',convert(varchar(25),doj,0) 'Date Of Joining' from stud2

CONNECTIVITY WITH MYSQL DATABASE: 


1. Import the required namespaces.
using System;
using System.Data;
using System.Data.Odbc;

2. Create a connection object.


string myConnectionString;
myConnectionString = “DRIVER = {MySQL ODBC 3.51 Driver}; SERVER =
localhost; DATABASE = project; UID = root;
55

PASSWORD = ‘’”
OdbcConnection odbcCon = new odbcConnection(myConnectionString)

3. Create a SQL query


string str;
str="Select * from Customer where UserID='admin’;

4. Create a Command object to run the SQL query


odbcCmd=new OdbcCommand(str,odbcCon);

5. DataReader to read the result


OdbcDataReader odbcReader;
String text, text2;
while (odbcReader.Read())
{
text = odbcReader["UserID"].ToString();
text2 = odbcReader[“FirstName”].ToString();
}

6. Close odbcReader and odbcConnection


odbcReader.Close();
odbcCon.Close();

Creating Setup File and also Embedded sqlserver


2005 Database

(viii) Create a windows application.


(ix) Select the menu “Project  Add Class“ and select “Installer
Class” in the template window.
(x) Click on the “Click Here To Switch to Code View” in the
opened page.
(xi) Select the menu “Project(Add Reference”
56

(xii) Select the “Browse” Tab in opened window and chose the file in following
location : -- “C:\Program Files\Common Files\System\Ole DB\
oledb32.dll”
(xiii) Again Select the menu “Project ( Add Reference” and select “adodb” in
the “.NET” tab.
(xiv) Write the the code in top of the file as:--
“ Using System.Collections; ”
(xv) And Below Write the code as:--
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
createDatabase();
}
private void createDatabase()
{
MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
ADODB.Connection cs = (ADODB.Connection)dataLinks.PromptNew();
cs.Open("", "", "", 0);
object missing = null;
string database = "SetupTestDatabase";
cs.Execute("create database " + database, out missing, 0);

cs.DefaultDatabase = database;
String comma = "create table ranjit_test(name varchar(50),
phone varchar(15))";
cs.Execute(comma, out missing, 0);
}

(xvi) Select the menu “File  Add  New Project”

(xvii) Choose “Setup and deployment ( Setup project” in the opened window.
(xviii) Click on “Custom Action” Icon in the “top and Right position” of the
“Solution Explorer” window.
(xix) Right Click on “Install” and select “Add Custom Action” then Choose
“Application Folder” in the combobox and click on “ Add Ouput” button.
As in Below Figure:---

((

(xx) select “Primary output” and click on “Ok” Button.


(xxi) Again Click on Ok Button in the message box.
(xxii) Again click on OK Button.
(xxiii) Now Right Click on “Setup1” and select the “Build” menu as--
57

(xxiv) After the “Build Successed” close the vs.net application.


(xxv) Execute the setup file.
(xxvi) Select “oledb provider for sql server” as:--

(xxvii) Type “Server name” select “Use Windows NT………” and click in ok
button not type any database name. as ----
58

(xxviii) Now we have found the in sql server automatically created one
database and one table.

How to shutdown the system on click event of button :(


(i) open a new windows application in c#.net
(ii) Drag and drop one button on te form.
(iii) Double click on the button and edit the code as :----

// Add reference the “system.management”

using System.Management;
namespace WindowsApplication24
{
public partial class Form1 : Form
{
private void btn_shutdown_Click(object sender, EventArgs e)
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass
("Win32_OperatingSystem");
mcWin32.Get();
// You can't shutdown without security privileges
59

mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams =
mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
}
}
}

You might also like