0% found this document useful (0 votes)
511 views

Interview Questions and Answers Book

This document provides an overview and introduction to an eBook about ADO.NET interview questions and answers. It discusses what topics will be covered in the eBook, including ADO.NET architecture, connected and disconnected architecture, data providers, using connection and command objects, data readers, datasets, and transactions. It also provides biographical information about the author, Shailendra Chauhan, who is an entrepreneur, author, architect, corporate trainer, and Microsoft MVP founder of the website DotNetTricks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
511 views

Interview Questions and Answers Book

This document provides an overview and introduction to an eBook about ADO.NET interview questions and answers. It discusses what topics will be covered in the eBook, including ADO.NET architecture, connected and disconnected architecture, data providers, using connection and command objects, data readers, datasets, and transactions. It also provides biographical information about the author, Shailendra Chauhan, who is an entrepreneur, author, architect, corporate trainer, and Microsoft MVP founder of the website DotNetTricks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

ADO.

NET Interview Questions & Answers

All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without
the prior written permission of the author.

The author of this book has tried his best to ensure the accuracy of the information described in this book.
However, the author cannot guarantee the accuracy of the information contained in this book. The author will
not be liable for any damages, incidental or consequential caused directly or indirectly by this book. Further,
readers should be aware that the websites or reference links listed in this book may have changed or disappeared
between when this book was written and when it is read.

All other trademarks referred to in this book are the property of their respective owners.

Release History
• Initial Release 1.0.0 - 24th June 2019

1
Page
About Dot Net Tricks
Dot Net Tricks is founded by Shailendra Chauhan (Microsoft MVP), in Jan 2010. Dot Net Tricks came into existence
in the form of a blog post over various technologies including .NET, C#, SQL Server, ASP.NET, ASP.NET MVC,
JavaScript, Angular, Node.js and Visual Studio etc.

The company which is currently registered by a name of Dot Net Tricks Innovation Pvt. Ltd. came into the shape
in 2015. Dot Net Tricks website has an average footfall on the tune of 300k+ per month. The site has become a
cornerstone when it comes to getting skilled-up on .NET technologies and we want to gain the same level of trust
in other technologies. This is what we are striving for.

We have a very large number of trainees who have received training from our platforms and immediately got
placement in some of the reputed firms testifying our claims of providing quality training. The website offers you
a variety of free study material in the form of articles.

Dot Net Tricks Courses


Master in-demand job skills with our step by step and project-based courses. Learn to start a new career, with our
curated learning paths tailored to today's developers and technology needs. Learn to code, prepare yourself for
interviews, and get hired!

We offer the eBooks in the following categories:

• .NET Development
• Frond-end Development
• Cloud
• DevOps
• Programming Languages
• Database - SQL and NoSQL
• Mobile Development and many more...

You can start learning free from here: https://www.dotnettricks.com/courses

Dot Net Tricks Pro

DotNetTricks Pro unlocks the access of DotNetTricks premium features like unlimited access to all courses, source
codes, assessments. Get help over email or phone. Upgrade your skills with curated learning paths tailored to
today's developers and technology needs. Learn new skills and discover the world of possibilities with step-by-
step guidance.
2
Page
Start your journey today to learn coding. Because learning to code is the first step and foreword to advance your
career. The detail about Dot Net Tricks Pro can be found here: https://www.dotnettricks.com/pro-membership

Dot Net Tricks Live Training


Instructor-led Training Programs

For a beginner who needs regular guidance, we have a fully packed Master Courses. They are almost equal to
semester courses taught in engineering colleges when it comes to length, breadth of content delivery, the only
difference instead of 5-6 months, they take approx. 16-weekend classes (2 months).

The detail about Master courses can be found here: https://www.dotnettricks.com/instructor-led-courses

Corporate Training

Dot Net Tricks having a pool of mentors who help the corporate to enhance their employment skills as per
changing the technology landscape. Dot Net Tricks offers customized training programs for new hires and
experienced employees through online and classroom mode. As a trusted and resourceful training partner, Dot
Net Tricks helps the corporate to achieve success with its industry-leading instructional design and customer
training initiatives.

Apart from these, we also provide on-demand boot camps and personalized project consultation.

The detail about Corporate Training can be found here: https://www.dotnettricks.com/corporate-training

Dot Net Tricks eBooks


Dot Net Tricks offer a wide range of eBooks on technical interviews Q&A. All eBooks are written by industry
experts and coaches. These eBooks will help you to prepare yourself for your next job within a short time. We
offer the eBooks in the following categories:

• .NET Development

3

Frond-end Development
Page

• Cloud
• DevOps
• Programming Languages
• Database - SQL and NoSQL
• Mobile Development and many more….

You can buy other eBooks from here: https://www.dotnettricks.com/books

Technical Recruiting
We provide full technical staffing service which suits our client needs. Our technical recruiters search across the
world to find highly skilled professionals that will fit our clients need. If you are looking for a job change, do share
your resume at [email protected]. Dot Net Tricks will help you to find your dream job in MNCs.

Join us today, learn to code, prepare yourself for interviews, and get hired!

4
Page
Dedication
My mother Mrs Vriksha Devi and my wife Reshu Chauhan deserve to have their name on the cover as
much as I do for all their support made this possible. I would like to say thanks to all my family members
Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to
readers or followers of my articles at https://www.dotnettricks.com/mentors/shailendra-chauhan to
encourage me to write this book.

-Shailendra Chauhan

5
Page
Introduction
Writing a book has never been an easy task. It takes a great effort, patience and consistency with strong
determination to complete it. Also, one should have a depth knowledge over the subject is going to write.
So, what where my qualification to write this book? My qualification and inspiration come from my enthusiasm
for and the experience with the technology and from my analytic and initiative nature. Being a trainer, analyst,
consultant and blogger, I have thorough knowledge and understandings of .NET technologies. My inspiration and
knowledge have also come from many years of my working experience and research over it.

What This Book Is


ADO.NET is an integral part of the .NET Framework which provides access to relational data, XML documents, and
application data. This book will teach you ADO.NET from scratch to advance with the help of Interview Questions
& Answers. Here, you will about the ADO.NET fundamentals, connection, command, data reader, datasets,
advanced datasets and transactions.

What You’ll Learn


This book is for .NET developers who are looking for a change or want to make a bright future in .NET technologies
stack. This book covers the interview questions on the following topics:

• ADO.NET Architecture.
• Connected and Disconnected Architecture.
• Data Providers and Connection Pooling.
• How to use Connection and command objects.
• Using DataReader and DataSets.
• Data Adapter and DataView.
• Using and Managing DataTable.
• Strongly typed datasets and untyped data sets.
• Use of Transaction in ADO.NET.

Our best wishes always with you for your learning and growth!
6
Page
About the Author
Shailendra Chauhan - An Entrepreneur, Author, Architect,
Corporate Trainer, and Microsoft MVP
He is the Founder and CEO of DotNetTricks which is a brand when it comes
to e-Learning. DotNetTricks provides training and consultation over an array
of technologies like Cloud, .NET, Angular, React, Node and Mobile Apps
development. He has been awarded as Microsoft MVP three times in a row
(2016-2018).

He has changed many lives from his writings and unique training programs.
He has a number of most sought-after books to his name which have helped
job aspirants in cracking tough interviews with ease.

Moreover, and to his credit, he has delivered 1000+ training sessions to professionals worldwide in Microsoft
.NET technologies and other technologies including JavaScript, AngularJS, Node.js, React and NoSQL Databases.
In addition, he provides Instructor-led online training, hands-on workshop and corporate training programs.

Shailendra has a strong combination of technical skills and solution development for complex application
architecture with proven leadership and motivational skills have elevated him to a world-renowned status,
placing him at the top of the list of most sought-after trainers.

“I always keep up with new technologies and learning new skills to deliver the best to my students,” says
Shailendra Chauhan, he goes on to acknowledge that the betterment of his followers and enabling his students to
realize their goals are his prime objective and a great source of motivation and satisfaction.

Shailendra Chauhan - “Follow me and you too will have the key that opens the door to success”

7
Page
How to Contact Us
Although the author of this book has tried to make this book as accurate as it possible but if there is something
strikes you as odd, or you find an error in the book please drop a line via e-mail.

The e-mail addresses are listed as follows:

[email protected]
[email protected]

We always happy to hear from our readers. Please provide your valuable feedback and comments!

You can follow us on YouTube, Facebook, Twitter, LinkedIn and Google Plus or subscribe to RSS feed.

8
Page
Table of Contents
ADO.NET Interview Questions & Answers ...................................................................... 1
Release History ....................................................................................................................................................1
About Dot Net Tricks ..........................................................................................................................................2
Dot Net Tricks Courses .......................................................................................................................................2
Dot Net Tricks Live Training ................................................................................................................................3
Dot Net Tricks eBooks ........................................................................................................................................3
Technical Recruiting ...........................................................................................................................................4
Dedication ...........................................................................................................................................................5
Introduction ........................................................................................................................................................6
About the Author ................................................................................................................................................7
How to Contact Us...............................................................................................................................................8

Introducing ADO.NET ..................................................................................................... 11


Q1. What is ADO.NET? ................................................................................................................................... 11
Q2. Explain the architecture of ADO.NET?..................................................................................................... 11
Q3. What are the advantages of using ADO.NET? ......................................................................................... 12
Q4. What is the difference between ADO and ADO.NET? ............................................................................. 12
Q5. What is connected environment in ADO.NET? ....................................................................................... 13
Q6. What is disconnected environment in ADO.NET? ................................................................................... 13
Q7. What are the most commonly used namespaces in ADO.NET?.............................................................. 14
Q8. What is the role of .NET Framework data Providers? ............................................................................. 14
Q9. What are the different types of data providers in .NET framework? ..................................................... 14
Q10. What are managed providers? ................................................................................................................ 15

Connection and Command ............................................................................................ 16


Q1. What is Connection Pooling? .................................................................................................................. 16
Q2. What are the pre-requisites for Connection Pooling? ............................................................................ 16
Q3. How can you enable or disable connection pooling?.............................................................................. 16
Q4. What is default maximum pool size in ADO.NET connection string?...................................................... 16
Q5. Write a sample code for ADO.NET connection to SQL Server................................................................. 16
Q6. What is Command Object? ...................................................................................................................... 17
9
Page

Q7. What are Command Object methods? .................................................................................................... 17


Q8. What is difference between SqlCommand and SqlCommandBuilder? ................................................... 17
Q9. What is SqlCommand Object? ................................................................................................................. 17
Q10. What is CommandType in SqlCommand? ............................................................................................... 18
Q11. What are ReadCommitted and ReadUncommitted Transactions? ......................................................... 18
Q12. What is difference between Optimistic and Pessimistic locking? ........................................................... 19

DataReaders and DataSets ............................................................................................. 20


Q1. What is DataReader in ADO.NET? ........................................................................................................... 20
Q2. What is DataSet in ADO.NET?.................................................................................................................. 20
Q3. What is difference between DataReader and DataSet?.......................................................................... 20
Q4. What is difference between DataSet and RecordSet? ............................................................................ 21
Q5. How can you determine the changes done in DataSet? ......................................................................... 21
Q6. What is Data Adapter? ............................................................................................................................ 21
Q7. How to use Data Adapter in ADO.NET? ................................................................................................... 21
Q8. What are basic methods of DataAdapter? .............................................................................................. 22
Q9. What is the use of AcceptChanges method in DataSet? ......................................................................... 22
Q10. What is the use of DataView? ................................................................................................................. 22
Q11. What are different methods associated with DataView? ....................................................................... 22
Q12. How can you sort DataTable using DataView? ........................................................................................ 22
Q13. How can you add multiple DataTable to a DataSet? ............................................................................... 22
Q14. What is difference between Clone and Copy methods of DataSet? ....................................................... 23
Q15. How can you delete a row from a DataTable? ........................................................................................ 23

Advanced DataSets and Transactions ............................................................................ 24


Q1. What is Strongly Typed DataSets?........................................................................................................... 24
Q2. What is UnTyped DataSets? .................................................................................................................... 24
Q3. What are the different methods in DataSet to manipulate with XML? .................................................. 24
Q4. What is the use of Transaction in ADO.NET? .......................................................................................... 24
Q5. How to create a Transaction in ADO.NET? .............................................................................................. 24

References ..................................................................................................................... 26
Learn. Build. Empower. .................................................................................................. 26
10
Page
1
Introducing ADO.NET
Q1. What is ADO.NET?
Ans. ADO.NET is an evolutionary improvement to Microsoft ActiveX Data Objects (ADO). ADO.NET is an
integral part of the .NET Framework which provides access to relational data, XML documents, and application
data.

Q2. Explain the architecture of ADO.NET?


Ans. ADO .NET Architecture is a multilayered architecture that has two main components- .NET Framework
Data Provider and DataSet. .NET provider has four main objects Connection, Command, DataReader and
DataAdapter while DataSet has two main objects DatTable and DataRelation as shown in below diagram.

11

.NET Framework Data Provider: They actually talk to the database to assist in data retrievals and updates.
Page
Class Description
Connection Connection represents a connection to the database system.
Command Represents SQL query or command to be executed at the database management system.
DataAdapter DataAdapter class connects to the database system, fetch the record and fill the DataSet. It
contains four different commands to perform database operations; Select, Update, Insert and
Delete.
DataReader A stream that reads data from the database in connected design.

DataSet: The DataSet is a local buffer of tables or a collection of disconnected record sets and hold actual data.
Its main components are given below:

Class Description
DataTable DataTable is used to contain the data in tabular form using rows and columns.
DataRow Represents a single record or row in DataTable.
DataRow DataRow Represents a single record or row in DataTable.
DataColumn DataColumn Represents a column or field of DataTable.
DataRelation DataRelation Represents the relationship between different tables in a DataSet.
Constraint Represents the constraints or limitations that apply to a particular field or column.

Q3. What are the advantages of using ADO.NET?


Ans. There are following advantages of using ADO.NET:

• Performance and scalability: ADO.NET offer high performance and scalability than ADO. In ADO.NET,
disconnected cached data in XML helps in performance and scalability
• Optimized SQL Provider: ADO.NET SQL Server Data Provider that is highly optimized for interaction with
MS-SQL Server. It uses SQL Server’s own TDS (Tabular Data Stream) format for exchanging information.
• XML Support (Data transfer in XML format): ADO.NET data is cached and transferred in XML (Extensible
Markup Language) format. XML provide fast access of data for desktop and distributed applications.
• Disconnected Model: In ADO.NET, the DataSet operates in an entirely disconnected fashion. The
disconnected model makes the DataSet to be unaware of the data source of its data. In this way you can
use an unlimited number of supported data sources to be plugged into code without any hassle.

Q4. What is the difference between ADO and ADO.NET?


Ans. Following are the major difference between ADO and ADO.NET.

ADO ADO.NET
ADO has RecordSet to access and manipulate data. ADO.NET has DataSet to access and manipulate data.
In RecordSet, there can be one table. To contains In ADO.NET, a DataSet can have multiple tables.
more than one tables, you need to perform inner join.
XML support is less as compared to ADO.NET XML support is high.
It supports only connected model. It supports both connected and disconnected model.
12
Page
Q5. What is connected environment in ADO.NET?
Ans. In a connected environment while querying or modifying the data source, you are connected to it. The
components of Connected environment are given below:

Q6. What is disconnected environment in ADO.NET?


Ans. In a disconnected environment, a subset of data is fetched from the main data store and stored in a
memory cache using DataSet. A DataSet can be modified independently, and the changes sync back to the main
data source. Disconnected environment components are given below:

13
Page
Q7. What are the most commonly used namespaces in ADO.NET?
Ans. Following are the most commonly used namespace in ADO.NET.

1. System.Data
2. System.Data.OleDb
3. System.Data.SqlClient
4. System.Data.OracleClient
5. System.Xml

Q8. What is the role of .NET Framework data Providers?


Ans. The .NET Framework data providers serve as a bridge between an application (presentation layer) and a
data source (data layer) that execute SQL commands as well as retrieve data by using a DataReader or a
DataAdapter.

Q9. What are the different types of data providers in .NET framework?
Ans. Following are the different data providers in .NET framework.

Provider Name Access Description


System.Data.SqlClient .NET Data Provider for SQL Server Provides access to Microsoft SQL Server 7.0
or later version
System.Data.OleDb .NET Data Provider for OLE DB Provides access to databases exposed by
using OLE DB.
14

System.Data.Odbc .NET Data Provider for ODBC Provides access to databases exposed by
using ODBC.
Page
System.Data.OracleClient .NET Data Provider for Oracle Provides access to Oracle database version 8
or later versions.

Q10. What are managed providers?


Ans. In ADO.NET a managed provider is similar to ODBC driver or OLEDB provider that performs operation of
communication with the database. ADO.NET currently provides two distinct managed providers.

• SQL Server managed provider: The SQL Server managed provider is used with SQL server and is a very
efficient way of communicating with SQL Server.
• OLEDB managed provider: OLEDB managed provider is used to communicate with any OLEDB compliant
database like MS Access, Oracle, DB2 etc.

15
Page
2
Connection and Command
Q1. What is Connection Pooling?
Ans. Grouping of database connections in cache to make them reusable is called connection pooling. You know
that opening new connections every time to a database is a time-consuming process. And so, connection pooling
enables us to reuse already existing and active database connections, whenever required. In this way it increases
the performance of our application.

Q2. What are the pre-requisites for Connection Pooling?


Ans. The prerequisites for connection pooling are there must be multiple processes to share the same
connection describing the same parameters and security settings. Also, the connection string must be identical.

Q3. How can you enable or disable connection pooling?


Ans. Using Pooling=true in connection string you can enable connection pooling. To disable connection pooling
set Pooling=false. By default it is enabled in an application.

<connectionStrings>
<add name="strCon" connectionString="Data Source=dotnet-tricks.com;Initial Catalog=dotnet-
tricks; Persist Security Info=True; Pooling=true; User ID=tricks;Password=123@dt"
providerName="System.Data.SqlClient"/>
</connectionStrings>

Q4. What is default maximum pool size in ADO.NET connection string?


Ans. The maximum pool size specifies the maximum number of connections allowed in the pool. The default
max pool size is 100.

Q5. Write a sample code for ADO.NET connection to SQL Server.


Ans. Following are the sample code in C# for ADO.NET Connection to SQL Server.

string strCon = "server=dotnet-tricks.com; uid=yourId;pwd=yourPwd; database=dbname";

SqlConnection conn = new SqlConnection(strCon);

try
16

{
conn.Open();// Open DB connection
Page

//Our source code here.


}
catch (Exception ex)
{
// Log Exceptions
}
finally
{
conn.Close(); // Close the connection
}

Q6. What is Command Object?


Ans. Each .NET Framework data provider included with the .NET Framework has a Command object which is
used to execute SQL commands like insert, update, delete, select, create, alter, drop etc. You can also call stored
procedures with the command object.

Q7. What are Command Object methods?


Ans. The command object has the following important methods:
1. ExecuteNonQuery(): It executes a SQL statement that doesn’t return any value like insert, update and delete.
The return type of this method is int and it returns the number of rows affected by a SQL statement.

2. ExecuteReader(): It executes a select a statement and return the rows returned by the select statement as a
DataReader. The return type of this method is a DataReader.

3. ExecuteScalar: It executes a SQL statement which returns a single value, like avg, min, max etc. The return
type of this method is object.

Q8. What is difference between SqlCommand and SqlCommandBuilder?


Ans. SqlCommand is used to execute all kind of SQL queries (DML & DDL). However, SqlCommandBuilder object
is used to build & execute SQL (DML) queries like select, insert, update & delete.

Q9. What is SqlCommand Object?


Ans. SqlCommand: SqlCommand is a collection of strings containing SQL statements which will be send to
database for various operations. SQL Commands can be of type Select, Insert, Delete, Update or Stored
procedures.

string strCon = "server=dotnet-tricks.com; uid=yourId;pwd=yourPwd; database=dbname";

SqlConnection conn = new SqlConnection(strCon);

try
{
conn.Open();// Open DB connection

string strSelect = "select * from dbo.Tbl_Employe";


SqlCommand cmd = new SqlCommand(strSelect, conn);
}
17

catch (Exception ex)


{
Page

// Log Exceptions
}
finally
{
conn.Close(); // Close the connection
}

Q10. What is CommandType in SqlCommand?


Ans. It specifies how a command string is interpreted. The different CommandType are: StoredProcedure,
TableDirect and Text.

• For Stored Procedures, CommandType should be specified as shown below:

SqlCommand cmd = new SqlCommand("dbo.Usp_GetEmployeeDetailById", conn);


cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@EmployeeID", "U00000001");

• For TableDirect, CommandType should be specified as shown below:

OleDbConnection conn = new OleDbConnection(Connection);

try
{
conn.Open();// Open DB connection

OleDbCommand cmd = new OleDbCommand("dbo.Tbl_Employe", conn);


cmd.CommandType = CommandType.TableDirect;

}
catch (Exception ex)
{
// Log Exceptions
}
finally
{
conn.Close(); // Close the connection
}

• For normal queries like select, CommandType is not specified.

string strSelect = "select * from dbo.Tbl_Employe";


SqlCommand cmd = new SqlCommand(strSelect, conn);

Q11. What are ReadCommitted and ReadUncommitted Transactions?


Ans. ReadCommitted: This is a state of transaction where changes in database made by a user can be reflected
to others only after the transaction is being committed by first user. By default, transactions are ReadCommitted.
This prevents dirty reads.

For example, if two persons are accessing same table, if one person executes an insert, other person will be able
to access the newly inserted row only after the first person commit the transaction.
18

ReadUncommitted: This is a state of transaction where changes in database made by a user can be reflected to
Page

others before the first user commits the transaction. Transactions running at the Read Uncommitted level do not
issue shared locks to prevent other transactions from modifying data read by the current transaction. This does
not prevent dirty reads.

Q12. What is difference between Optimistic and Pessimistic locking?


Ans. Optimistic: In Pessimistic locking when a user wants to update the data it locks the records and till then
no one can modify the data. Other users can only view the data when there is pessimistic locking

Pessimistic: In Optimistic locking multiple users can open the same record for modification, thus increase
maximum concurrency. The record is only locked when it is modified by someone and starts committing it to the
database.

19
Page
3
DataReaders and DataSets
Q1. What is DataReader in ADO.NET?
Ans. A DataReader object is a forward-only and read-only cursor. It needs a live connection with the data
source to fetch the result.

Key points about DataReader

1. DataReader object cannot be directly instantiated. Instead, it must be called by ExecuteReader method
of the Command object.
2. By using DataReader your application performance can be increased since it retrievs data as soon as it is
available, and by default it stors only one row at a time in memory.
3. A DataReader provides fast access when a forward-only sequential read is needed.
4. Be sure to close the connection when done using data reader. Otherwise, the connection stays alive until
it is explicitly closed.

Q2. What is DataSet in ADO.NET?


Ans. A DataSet is a set of tables or a collection of disconnected record sets which allows you to store data for
using in your application. In fact, a DataSet is disconnected cache store. A DataSet structure is similar to a relational
database containing tables, rows, and columns. Also, it can have constraints and relationships between the tables
as we have in database.

Q3. What is difference between DataReader and DataSet?


Ans. Following are the key difference between DataReader and DataSet.

DataReader DataSet
Works in connected mode only. Works in disconnected mode only.
Can navigate forward only. Can navigate backward and forward.
Data is read only. Data is editable.
Can contain only one row/record at a time. It cached the entire data. Hence contain multiple records.
Faster as compared to DataSet. Slower as compared to DataReader.
Need to open or close connection explicitly. Do not need to open or close the connection.
20
Page
Q4. What is difference between DataSet and RecordSet?
Ans. The difference between DataSet and RecordSet is given below:

DataSet RecordSet
Supports disconnected approach. Supports connected approach.
A DataSet can represent a relational database in A RecordSet is able to load the structure and data of only
memory along with tables, relations, and views. one table at a time.
Data in a DataSet is cache, rather than being A RecordSet can contain one record at a time.
loaded on demand.
DataSet can be transmitted over http protocol. A RecordSet cannot be transmitted over http protocol.
There is no concept of cursor in DataSet There is concept of cursor in RecordSet
You can use foreach loop to move through the RecordSet have current record pointer and so you cannot
data. use foreach loop.

Q5. How can you determine the changes done in DataSet?


Ans. In DataSet changes can be determine by using following methods:

1. GetChanges()– It returns a copy of the DataSet containing all changes made to it since it was last loaded,
or since the last time AcceptChanges was called.
2. HasChanges()– It returns a boolean value (true or false) to indicates any changes occurred to DataSet
including new, deleted, or modified rows. If changes occur, it returns true otherwise returns false.
3. RejectChanges()– It rolls back all the changes made to the DataSet object since it was created, or since
the last time AcceptChanges was called.

Q6. What is Data Adapter?


Ans. A Data adapter is a part of ADO.NET data providers. It is used to communicate between a data source and
a dataset. It uses the Connection object to connect to the data source, and it uses Command objects to retrieve
data from database and resolve changes to the database.

Q7. How to use Data Adapter in ADO.NET?


Ans. The example code for Data Adapter is given below:
string strCon = "server=servername; uid=UserName; pwd=Password; database=dbname";
SqlConnection conn = new SqlConnection(strCon);
conn.Open();

string StrSql = "Select * from tbl_Employee";


SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = new SqlCommand(StrSql, conn);
DataSet ds = new DataSet("ds_Employees");
Adapter.Fill(ds);
21

// Code to update data in a data source


ds.Tables["tbl_Employee"].Rows[0]["Name"] = "Asif";
Page

Adapter.Update(ds, "tbl_Employee");
Q8. What are basic methods of DataAdapter?
Ans. Following are the methods of DataAdapter:

Methos Description
Fill This method fills data records from a DataAdapter to a DataSet object by executing the Select
statement.
FillSchema This method adds a DataTable with its schema to a DataSet. It creates an empty table in the
DataSet object with all the corresponding constraints.
Update This executes the Insert, Update, or Delete SQL statement to update the original data source
with the changes made to the content of the DataSet.

Q9. What is the use of AcceptChanges method in DataSet?


Ans. This method commits all the changes made to the DataSet since it was loaded or since the last time
AcceptChanges was called.

Q10. What is the use of DataView?


Ans. DataView is data container that contain user define view of tables. A complete table or a small section of
table depending on some criteria can be presented by an object of the DataView class. You can use this class to
sort and find data within DataTable.

Q11. What are different methods associated with DataView?


Ans. The different methods associated to DataView are as:

1. Find()- Finds a row in a DataView by using sort key value.


2. FindRows()- Uses the sort key value to match it with the columns of DataRowView objects. It returns an array
of all the corresponding objects of DataRowView whose columns match with the sort key value.
3. AddNew()- Adds a new row to the DataView object.
4. Delete()- Deletes the specified row from the DataView object according to the specified index.

Q12. How can you sort DataTable using DataView?


Ans. By following way, you can use DataView for filtering and sorting data in a DataTable.

DataTable DtEmployee = new DataTable();

//sorting done by Name column using DataView


DtEmployee.DefaultView.Sort = "Name";

Q13. How can you add multiple DataTable to a DataSet?


Ans. By following way, you can add multiple DataTable to a DataSet.
22
Page
//Creating 1st DataTable
DataTable DtEmployee = new DataTable("Employee"); //Create Table name

// Adding Column To Employee DataTable


DtEmployee.Columns.Add("ID");
DtEmployee.Columns.Add("Name");

//Adding record to Employee DataTable


DtEmployee.Rows.Add("A0000001", "Shailendra Chauhan");
DtEmployee.Rows.Add("A0000002", "Asif Iqbal");

//Creating 2nd DataTable


DataTable DtStudent = new DataTable("Student"); //Create Table name

// Adding Column To Student DataTable


DtStudent.Columns.Add("RollNo");
DtStudent.Columns.Add("Name");

//Adding record to Student DataTable


DtStudent.Rows.Add(1, "Peter Smith");
DtStudent.Rows.Add(2, "Jhon Doe");

//Adding Tables to DataSet


DataSet ds = new DataSet();
ds.Tables.Add(DtEmployee);
ds.Tables.Add(DtStudent);

Q14. What is difference between Clone and Copy methods of DataSet?


Ans. The difference between Clone and Copy methods is given below:

Clone Copy
The Clone() method copies only the structure of a The Copy() method copies the structure as well as
DataSet. The structure of a DataSet includes all the the data stored in the DataSet.
relations, constraints and the DataTables.

Q15. How can you delete a row from a DataTable?


Ans. Using Delete method you can delete a row from DataTable as given below:

DataTableName.Rows[index].Delete();
DataTableName.AcceptChanges();

23
Page
4
Advanced DataSets and
Transactions
Q1. What is Strongly Typed DataSets?
Ans. A Typed DataSet is a class that derives from a DataSet and contains all the methods, events, and properties
of a DataSet. It is stored in an .xsd file and type checking is done at design time using the .xsd definitions. A Typed
dataset binds with the database tables at design time and contains all the schema information at design.

Q2. What is UnTyped DataSets?


Ans. An UnTyped DataSet is an instance of class System.Data.DataSet. It binds with the table at runtime and at
runtime and there no corresponding built-in schema. So, there is not type checking.

Q3. What are the different methods in DataSet to manipulate with XML?
Ans. The methods to create, read and return XML in DataSet are given below:

1. ReadXml()- Reads XML document into a DataSet object.


2. GetXml()- Returns a string containing an XML document.
3. WriteXml()- Writes an XML data to disk.

Q4. What is the use of Transaction in ADO.NET?


Ans. A transaction is useful when you want to execute a set of commands in ADO.NET in a scope as a single
unit. If one of the operations failed in the group, all of the database updates would be rolled back i.e. there is no
change in the database.

Q5. How to create a Transaction in ADO.NET?


Ans. In ADO.NET a transaction can be opened as given below:
SqlConnection con = new SqlConnection("<your connection string here>");
con.Open();

//start transaction
24

transaction = con.BeginTransaction();
try
Page

{
SqlCommand cmd = new SqlCommand("<your sql statement1 here>", con, transaction);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("<your sql statement2 here>", con, transaction);
cmd.ExecuteNonQuery();

//commit db changes
transaction.Commit();
}
catch (SqlException sqlError)
{
//rollback/undo db changes
transaction.Rollback();
}
con.Close();

25
Page
References

This book has been written by referring to the following sites:

1. https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/- Microsoft Docs - ADO.NET


2. https://stackoverflow.com/questions/tagged/ado.net - Stack Overflow - ADO.NET
3. https://www.dotnettricks.com/learn - Dot Net Tricks

Learn. Build. Empower.

Master in-demand job skills with our step by step and project-based courses. Learn to start a new career, with our
curated learning paths tailored to today's developers and technology needs. Learn to code, prepare yourself for
interviews, and get hired!

START LEARNING FOR FREE

Join the community of 300,000+ developers

26
Page

You might also like