The document discusses ADO (ActiveX Data Objects) and how it facilitates communication between programming languages and data sources through intermediate components like drivers and providers. It explains different types of drivers like JET and ODBC drivers and their uses. It also discusses providers, and how they address some limitations of drivers. The document then introduces ADO.NET as a redesign of ADO with managed providers for .NET languages. It discusses various classes used for data access in ADO.NET. Finally, it explains concepts like connections, commands, data readers, datasets, and data adapters which are used for connecting to data sources and managing data in ADO.NET applications.
1. ADO (ACTIVEX DATA OBJECT)
DATA SOURCE COMMUNICATION:
Data source is a place where we can store the information which can be anything like files, databases,
indexing servers etc….
Languages can’t be communicate with data sources directly because each data source adopts a different
protocol for communication.
Language …… data source is not possible.
To facilitate the process of communication ms has provided the solution in the form of intermediate
components like “drivers and providers”.
Language – drivers or providers – data source
DRIVERS:
These were designed traditionally for communicating with databases which are of two types again.
1. JET drives [joint engine technology].
2. ODBC drivers [open data source connectivity].
1.JET Drivers:
It is designed communicate with local databases.
Ex: Application – JET drivers – local db (FoxPro, dbase).
Local db: those are loaded in client application memory.
2.ODBC Drivers:
These were designed to communicate with remote databases like SQL server,Oracle,Ingress etc..
Application – ODBC drivers – remote db’s (sql server, oracle , ingress).
Drawbacks of drivers:
As a driver is not part of an application first it should be explicitly install on the machine
where the applications installed & then configure with application.
Initially drivers were design only for databases communication.
PROVIDERS:
To address the problem in drivers ms has provided one more solution known as “OLEDB
providers “*Object Linking and Embedding data base+.
1
2. Providers were designed for data source communication and they becomes a part of your
application which doesn’t required explicit installation and configurations.
Application – OLEDB drivers – data sources (files, databases, indexing servers).
Note: both the drivers & providers suffers from a common problem i.e as they were designed using
native code languages Leeds to platform dependency , purely for windows.
Because of support for native language code the classical visual basic language wasn’t able to make
use of the drivers & providers directly. So ms has provided some intermediate components for the
process of communication as following.
Visual basic – DAO – JET drivers – Local DBS
RDO – ODBC driver s – Remote dbs
ADO – OLEDB providers – data sources
ADO.NET:
Ado.net is a collection of managed providers to communicate with data sources from .net
languages.
When .net was introduced to communicate with data sources the best out of traditional 3
technologies ado’s has been taken out & re designed as ado.net.
Ado.net provides various classes which can be used for communicating with data sources
under the following namespaces.
System.data;
System.Data.Oledb;
System.Data.Sqlclient;
System.Data.OracleClient;
System.Data.Odbc;
System.Data:
It’s a collection of classes used for holding & managing the data on client machine. Classes under
the namespaces are: dataset, data table, data row, data column, data view & data relation.
System.Data.Oledb:
It’s a collection of classes used for communicating with any data source.
System.Data.Sqlclient:
2
3. It’s a collection of classes used for communicating only for Sql server db.
System.Data.Oracle client:
It’s a collection of classes used for communicating only with Oracle db.
System.Data.Odbc:
It’s a collection of classes used for communicating with traditional ODBC-drivers which will in turn
communicate with data sources.
All the above 4 namespaces contains same set of classes as following:
Connection, command, data reader, data adapter, command builder & parameter.
Note: each class was referred by prefixing with the namespace before the class for distinguishing
b/w each other as following:
Oledbconnection
Sqlconnection
OracleConnection
OdbcConnection
Difference between ADO AND ADO.NET
ADO
It’s a collection of unmanaged providers to communicate with data sources.
It is a platform dependency
ADO.NET
It’s a collection of managed providers to communicate with data sources.
It is a platform independency
HOW TO CONNECT/CREATE DATABASE
HOW TO CREATE TABLE
HOW TO INSERT DATA
Every operation we perform on data source has 3 activities involved in it:
Establish a connection
Applying a Statement
Expecting the result
Establish a Connection:
3
4. In this process we open a channel for communication with the target machine to perform our
operations to open the channel for communication we use the “connection class”.
Connection()
Connection (string connection string)
Connection String:
it’s a collection of attributes that are used for connecting with target machine . those are:
- Provider
- Data source
- Usserid & password
- Database or initial catalog
- Trusted_connection
- Dsn
Provider:
As we were aware a provider is required for communicating with data sources we use a
separate provider for each data source to communicate.
Name of providers:
Oralce - Msdaora
Sql server – Sqloledb
MS-Access (or) – MS.Excel Microsoft.jet.oledb.4.0
Indexing server - msidxs
Data source :
It is the IP address (or) name of target machine where the data source (or) database is
present
The doesn’t require to be specified if it was on the local machine.
User id & password:
As db’s are secured places for string data to connect with them we require a valid user
name & password.
Oracle - scott/tiger
Sqlserver - sa/<blank>
Database(or) initial catalog and trusted _ connection attributes will be used only while
connecting with sql server.
Methods & properties under connection class:
Open(): a method to open the connection.
4
5. Close(): a method to close the connection.
State; a property to find states of the connection.
Connection string: a property to get (or) set the connection string
The object of class connection can be created in any of the following ways:
Connection con=new connection();
Con.connectionstring=”<con str>”;
(Or)
Connection con=new connectionstring=”<con str”>
CONNECTING WTH SQL SERVER
SQL SERVER is a collection of users & databases where user can have one or more databases of his own.
So, while connecting from a .NET application to SQL SERVER in the connection string we explicitly
require to specify the name of the database we want to connect either by using database (or) Initial
catalog attributes.
While connecting with SQL SERVER we have two different ways of authentication.
1. WINDOWS AUTHENTICATION.
2. SQL AUTHENTICATION.
In this SQL SERVER OS credentials to connect with server. So, we don’t require to supply them again.
Where in case of SQL authentication we require to explicitly provide user id and password.
While connecting from a .net application to sql server in windows authentication in place of user id &
password attributes we need to use “Trusted _Connection=True”
CONNECTION STRING FOR SQL SERVER AUTHENTICATION
FOR WINDOWS AUTHENTICATION
For c sharp:
con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;Integrated Security=True");
For vb:
con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;Integrated Security=True");
FOR SQL AUTHENTICATION
5
6. “Provider=sqlOledb; user Id=sa; password=<pwd>; databases=<dbname>[; data source=<server
name>+”
CREATING A DATABASE ON SQLSERVER:-
GO TO START MENU - Programsmicrosoft sql server sql server management studio , click on it
to open and provide authentication details to login.
Once the studio is open in the left and side we get a window object explorer [F8] , in that right click on
the node databases and select “NEW DATABASES” which opens a window asking for the name enter
name as csharp and click ok.which adds db under database node.
Now expand your charp and dbnode, right click on tables node & select “NEW TABLE” which opens a
window asking for column names & datatype, enter anything which you want.
NOTE:-select status column & go into ccolumn properties in the bottom and seet “default value (or)
Binding” property as 1, which takes the default value for status as true.
Click on the save button on the top of studio . which will prompt for table name ,enter name as
“students” & click OK. Which adds table under tables node.
Now right click on the table created & select “OPEN TABLE” which opens a window under it enter the
data we must ignoring photo & status columns &close the studio.
PROGRAM TO CHECK WHEATHER DATABASE IS CONNECTED OR NOT
SqlConnection con;
private void Form2_Load(object sender, EventArgs e)
{
con =new SqlConnection ("Data Source=.SQLEXPRESS;Initial
Catalog=sjcet;Integrated Security=True");
con.Open ();
MessageBox .Show(con.State .ToString ());
con.Close();
MessageBox.Show(con.State.ToString());
}
APPLYING A STATEMENT:
in this process we send on instruction to the data source specify the type of activity that has to be
preferred in the form of an sql statement like select, insert , update and delete.
We use command class for applying a statement:
Command()
Command(string stmt, connection con)
Properties of command class:
6
7. 1.connection :
To set (or)get the current connection object associated with command.
2.command text:
To set (or) get the current statement associated with command.
The object of command can be created as below:
Command cmd=new command();
cmd.connection=<con>;
cmd.command text=”<sql stmt>”;
(or)
Command cmd=new command(“<sql stmt>”,con);
METHODS OF COMMAND CLASS:
Name of method Return type
ExecuteReader() - Datareader
ExecuteScalar() - object
ExecuteNonquery - int
After creating the object of command class we need to call any of these 3 methods to execute the
statement.
1.ExecuteReader():
Call executereader method when ever we want to execute a select statement that returns values
in the form of rows & columns so that data comes & statements under data reader which is a class
modelation table.
2. ExecuteScalar():
Call execute scalar method when ever we want to execute a select statement that returns single
value result which captures the data under an object variable.
Note: we can use execute scalar method for executing a select statement that returns rows and
columns also. But we get only the first row and first column value as output.
3. ExecuteNonQuery():
7
8. Call execute non query method when ever we want to execute non-query statements [DML
statements] like insert, update and delete so that the no.of rows been effected is returned as
an integer.
Note: the above process of calling an appropriate method in an appropriate case is our
third activity expecting of the results.
DATA READER
It was a class model on table that can be used for holding data on client machine.
FEATURES:
Faster access to data from the data source as it was connection oriented.
It can hold multiple tables in it at a time .To load multiple tables we need to pass multiple select
statements as arguments to command separated by a semi-colon.
Example: cmd = new SqlCommand("select * from Table1","select * from Table1",con);
DataReader dr=cmd.ExecuteReader();
NOTE:-use the NextResult() method on data reader object to navigate from current table to next table.
eg:dr.NextResult();
ACCESSING DATA FROM A DATA READER
Data reader is a class which is modelled on table to access the data from datareader it provides us
following methods:-
Read()bool
Used for moving the record pointer from current location to next row , after moving the pointer
it will return the status specifying values were present in the row to which it has moved, that will be true
if present & false if not present.
Getvalue(int index)object
Used for picking the field value from the row to which pointer was pointing by specifying
column index position.
Note:-we can also access data in the form of single dimensional array also,either by specifying column
index position (or) name, as following:
<dr>[index]object
<dr>[colname]object
GetName(int index)string
Returns name of the column for specified index.
8
9. Drawbacks of data Reader:
It was designed in connection oriented which requires a permanent connection with data source to
access the data if the connection was closed we can’t access the data, which will be a burden on db
servers when multiple clients were accessing data from it.
It provides only forward navigation i.e. allow to go either to next record on table but not to previous
record (or) table.
It was a read only object which will not allow any changes on data present in it.
PROGRAM TO ACCESS DATA AND DATA FIELD NAMES
using System.Data.SqlClient;
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
private void Form1_Load(object sender, EventArgs e)
{
con= new SqlConnection ("Data Source=.SQLEXPRESS;Initial Catalog=sjcet;Integrated
Security=True");
cmd = new SqlCommand("select * from Table1",con);
con.Open();
dr=cmd.ExecuteReader();
label1.Text = dr.GetName(0);
label2.Text = dr.GetName(1);
label3.Text = dr.GetName(2);
label4.Text = dr.GetName(3);
showdata();
}
private void showdata()
{
if (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
textBox3.Text = dr[2].ToString();
textBox4.Text = dr[3].ToString();
}
else
MessageBox.Show("last record");
}
private void button1_Click(object sender, EventArgs e)
{
rno = 0;
showdata();
}
}}
9
10. BEFORE AFTER
DATASET
It was an another class provided for holding & managing data on a client machines apart from
datareders. Dataset class was present in System.Data namespace.
FEATURES
It was also capable of holding mltiple tables.
It was designed on disconnected architecture which doesn’t reqquire permanent connection with
datasource for a holding the data.
It provides scrollable navigation which allows to move in any diection.
It was updatable , i.e changes can be performed on data present in it.
Using datasets:
The class which is responsible for loading data into data reader from a data source is “command” in the
same way data adapter class is used for communication b/w data source and data set.
Data reader command<--data source.
Data set data adapter <– data source.
ACCESSING DATA FROM DATASET
Dataset is a collection of Tables where each table is represented as a class dataTable & identified by
index position (or) name.
Connections:-(COLLECTION OF TABLES)
10
11. <dataset>.Tables[index] or Tables[name]
Ds.Tables[0] or ds.Tables*“students”+
Every Datatable is again a collection of rows & columns where each row is represented as a class
DataRow & identified by it’s index postion. Each column is represented as a class DataColumn &
identified by index position or name.
DATA READER AND DATASET DIFFERENCES
Data Reader is a forward only and read only data
Data Set is used to maintain relationships between multiple tables.
Data Reader can't persist the data
Data Set can persist the data
Data Reader (connection oriented) is a read only and forward only record set which will have the data
retrieved based on the select statement. we can't do DML operations through Data Reader.
DATA TABLE
(COLLECTION OF ROWS(DATAROW))
<dataTable>.rows[index] (or) rows[name]
ds.tables[0].Rows[0]
(COLLECTION OF COLUMNSS(DATACOLUMN))
<dataTable>.columns[index] (or) columns[name]
ds.Tables[0].columns[0] (or) ds.Tables*0+.columns*“sno”+
REFERING TO A CELL UNDER DATATABLE:-
<dataTable>.Rows[rows][col]
ds.Tables[0].columns[0] [0] (or) ds.Tables*0+.Rows*0+*“sno”+
DATA ADAPTOR
In the same way data adapter class is used for communication b/w data source and data set.
Data set data adapter <– data source.
Connections:
DataAdaptor(string stmt, Connection con)
11
12. DataAdaptor(command cmd)
Eg:- DataAdaptor da=new DataAdaptor(“<sql stmt>”’con);
adap = new SqlDataAdapter("select * from empdetails", con);
METHODS OF DATADAPTOR
FILL(Dataset ds,string tname)
UPDATE(Dataset ds,String tname)
Fill is for loading data from DataSource to DataSet.
Update is to transfer changes made on data from DataSet to DataSource.
DataAdaptor is internally collections of 4 commands in it:
Select command, Insert command, Update command, Delete command
When we call fill method on a Adaptor following things takes place
1) Opens a connection with the DataSource.
2) Executes the select command under it & loads data from DataSource to DataSet.
3) Closes the connection with DataSource.
As we are DataSet is updatable, once the data is loaded intop it we can make changes on it like adding
(or) modifying (or) deleting of records.
After performing changes on DataSet if we want to send these changes back to the DataSource we need
to call Update method on adaptor which performs the following;-
1) Reopens a connection with the DataSource.
2) Changes which ae made on DagaSet will be sent back to DataSource, where in this process it
will make use of insert,update and delete commands of adaptor.
3) Closes the connection with DataSourcce.
PROGRAM TO GET DATASET IN GRIDVIEW
using System.Data.SqlClient;
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.SQLEXPRESS;Initial
Catalog=sjcet;Integrated Security=True");
12
13. adap = new SqlDataAdapter("select * from Table1", con);
con.Open();
ds = new DataSet();
adap.Fill(ds, "empdetails");
dataGridView1.DataSource = ds.Tables[0];
}
}
}
DATA GRID VIEW
It is a control which can display data in the form of Table i.e, rows & columns.
We can directly bind the datatable to the control by making use of it’s datasource property..
DataSource=<dataTale>
Eg:-datagridview1.DatSource=ds.Tables[0];
Datagridview control is updatable which will allow us to add , modify (or) delete records.
The speciality of it is any changes we perform on data of the control reflex directly into the DataTable to
which it was bound.
PROGRAM TO UPDATE DATASET IN GRIDVIEW
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder cmd;
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.SQLEXPRESS;Initial
Catalog=sjcet;Integrated Security=True");
adap = new SqlDataAdapter("select * from Table1", con);
con.Open();
cmd = new SqlCommandBuilder(adap);
ds = new DataSet();
adap.Fill(ds, "Table1");
dataGridView1.DataSource = ds.Tables[0];
}
13
14. private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
cmd2 = new SqlCommandBuilder(adap);
adap.Update(ds, "Table1");
MessageBox.Show("database saved succesfully");
}
}
}
FILLING DATA PRESENT UNDER DATASET
To filter the data present under dataset we have two different approaches
1) FIND METHOD,
2) DATA VIEW CLASS
FIND METHOD
It was capable of filtering the data basing on the primary key column of table which can retrieve only a
single row.
DATAVIEW CLASS
It was capable of filtering the data basing on any column of the table and retrieves multiple records.
Dataview is a class which was modeled on the object view of databse.which will never contain any
information init . It only act as a mediator between DataProvider and DataContainer.
Views also known as Logical Tables because they look like a table but never contains information init
physically.
14
15. The dataview also place the same role of a view in our .NET applications which can act as a mediator
between the dataprovider,dataset- and DataConsumer (like gridview,textbox,combobox e.t.c…)
USING A DATAVIEW
To make use of dataview we follow the below process:
Step(1):create a datview by using default view property of datatable class.which creates the view with
the same structure of the table of which it was called “DataTable”
Datatable
Defaultview DataType(returntype)
Ex.DataView dv=ds.Tables*“emp”+.DefaultView;
Step(2): After view gets created specify the condition to filter using the RowFilter property of DataView
class.
DataView:
RowFilter=<condition>
Ex.dv.RowFilter=”job=’manager’”
dv.Rowfilterr=”sal>250”
MULTI PLE GRID VIEW USING COMBOBOX
BEFORE FILTERING
15
16. AFTER FILTERING BASED ON DEPTNO = 412
SqlConnection con;
SqlDataAdapter da;
DataSet ds;
bool flag = false;
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.SQLEXPRESS;Initial
Catalog=sjcet;Integrated Security=True");
da = new SqlDataAdapter("select * from dept", con);
ds=new DataSet ();
da.Fill (ds,"dept");
da.SelectCommand .CommandText ="select * from emp";
da.Fill (ds,"emp");
comboBox1 .DataSource =ds.Tables ["dept"];
comboBox1.DisplayMember = "deptno";
dataGridView1.DataSource = ds.Tables["emp"];
flag = true;
}
16
17. private void comboBox1_SelectedIndexChanged(object sender, EventArgs
e)
{
if (flag)
{
DataView dv = ds.Tables["emp"].DefaultView;
dv.RowFilter = "deptno=" + comboBox1.Text;
}
}
PROGRAM USING ALL THE ABOVE COMMANDS (ADAPTOR & COMMAND ):
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter adap;
DataSet ds;
private void Form2_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.sqlexpress;Initial
Catalog=KINGS;Integrated Security=True");
con.Open();
MessageBox.Show(con.State.ToString());
loaddata();
con.Close();
}
private void loaddata()
{
adap = new SqlDataAdapter("select * from emp2", con);
ds = new DataSet();
//adap.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adap.Fill(ds);
DataGridView1.DataSource = ds.Tables[0];
}
17
19. private void BTNCLEAR_Click(object sender, EventArgs e)
{
TextBox1.Text = textBox2.Text = textBox3.Text = textBox4.Text = "";
TextBox1.Focus();
}
PROGRAM USING ALL THE ABOVE COMMANDS(ADAPTOR & COMMAND BUILDER):
SQLCOMMANDBUILDER :-if update method has to work datadaptor first requires three commands
under it i.e' insert,update and delete which should be written by programmer manually or generate
them with the help of a class command bulder.
command builder class if given with An adaptor that contains a select Command in it will write the
remaining three commands for adaptors.;
Note:- command builder can generate us update and delete commands for agiven select command only
if the table contains a keycolumn in it.
syntax:- CommandBuilder (DataAdaptor,ds)
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
SqlCommandBuilder cmd2;
int rno;
private void Form1_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=.sqlexpress;Initial
Catalog=KINGS;Integrated Security=True");
adap = new SqlDataAdapter("select * from empdetails", con);
con.Open();
ds = new DataSet();
// adap.MissingSchemaAction = MissingSchemaAction.AddWithKey;
MessageBox.Show(con.State.ToString());
adap.Fill(ds, "empdetails");
19
24. Small task about college using grid view and login
Step1 : take 3 forms (form 1 name it as form1, form 2 name it as homepage, form3 name it as reg.
Step2: in form1 design (panel,2 labels and 2 text boxes).
24
25. SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
private void button1_Click(object sender, EventArgs e)
{
con =new SqlConnection ("Data Source=.sqlexpress;Initial
Catalog=bank;Integrated Security=True");
da=new SqlDataAdapter ("select * from Login",con);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Homepage f = new Homepage();
f.Show();
}
else
{
MessageBox.Show("invalid login");
}
25
26. }
private void Form1_Load(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
Reg f = new Reg();
f.Show();
}
}
Step 3: in home page form take(labels, picture box,menustrips)
Step 4 : in registration form take( label, text box, rich text box, button, grid view).
26
30. using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace images_wiapp
{
public partial class Form1 : Form
{
30
31. SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
MemoryStream ms;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new
OpenFileDialog();
ofd.Filter = "image files|*.jpg;*.png;*.gif";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.Cancel)
return;
pictureBox1.Image=Image.FromFile(ofd.
FileName);
textBox1.Text=ofd.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;Initial
Catalog=sai;Integrated Security=True" );
ms = new MemoryStream();
pictureBox1.Image.Save(ms,
System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(pic_arr, 0, pic_arr.Length);
cmd = new SqlCommand("insert into
tbl_image(imgPath,imgImage)values(@imgPath,@imgimage)", con);
cmd.Parameters.AddWithValue("@imgPath", textBox1.Text);
cmd.Parameters.AddWithValue("@imgimage",pic_arr);
con.Open();
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("image added successfully");
}
else
{
MessageBox.Show("not inserted");
}
}
private void button3_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
31
32. }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
32
33. using System.IO;
namespace images_wiapp
{
public partial class Form2 : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
SqlDataReader dr;
MemoryStream ms;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;Initial
Catalog=sai;Integrated Security=True" );
//cmd = new SqlCommand("select imgPath from tbl_image where imgPath='" +
listBox1.SelectedItem + "'", con);
cmd = new SqlCommand("select imgPath from tbl_image", con);
con.Open();
try
{
dr=cmd.ExecuteReader();
while(dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CHETAN-11SQLEXPRESS;Initial
Catalog=sai;Integrated Security=True");
cmd = new SqlCommand("select * from tbl_image where imgPath='" +
listBox1.SelectedItem + "'", con);
con.Open();
SqlDataReader dr;
33
34. try
{
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] picarr = (byte[])dr["imgimage"];
ms=new MemoryStream(picarr);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
different overloads of Dataadapter.Fill() Method
that Dataadapter is working just like a bridge between a datasource and dataset. One of the method of
Dataadapter is Fill() Method.
It can be overloaded in 5 different ways.
First Overload
Dataadapter.Fill(ds) here fetches the data from tblMobile and fills in the DataSetds.
Output
On clicking the button Fill DataSet, the dataadapter fills the dataset and finally, the GridView shows all the records
present in the dataset ds.
34
35. Second Overload
Here Dataadapter.Fill(dt) fetches records from tblMobile and fills in the datatable named dt.
Output
On clicking the button Fill DataTable, the dataadapter fills the datatable and finally Gridview displays all the
records present in the datatable.
35
36. Third Overload
Here a datatable named nameOfDataTable has been filled by the dataadapter.Fill() method. As this datatable is
within the dataset, we can use the commented line also to fill the gridview. Let me be clear here,
To set the datasource of the gridview control we can use:
1. ds.Tables[0] //valid
2. ds.Tables["nameOfDataTable"] //valid
As this is the first table of the dataset, so we can use ds.Tables[0], otherwise we can use the table name to indicate
which table i need to access.
36
37. Output
Fourth Overload
This overload takes 3 parameters. The types of parameters are int,int and datatable. Here first parameter is the
starting record, second parameter is the maximum number of record and the last parameter is the datatable
where we have to fill the records. The range from which the records are to be fetched are mentioned here using
the parameters.
Output
37
38. Fifth Overload
At last, this overload takes 4 parameters. The types of parameters are dataset,int,int,string. The first parameter is
the name of the dataset, second parameter is the starting record number, third parameter is the maximum
number of records and the last parameter is the name of the table.
At first ds1 is filled with all the records of tblMobile. And then, dataadapter.Fill() method has filled the
datatable nm with the specified range of records.
Following figure shows the contents of dataset ds1. It is having all the records of tblMobile.
38
39. Now, the dataadapter object da1 takes 4 parameters and fills the datatable named nm with the records of
specified range.
Output
39