Sei sulla pagina 1di 179

ADO.net Tutorials- http://r4r.co.

in
R4R provide basic ADO.Net Tutorials concept with ADO.Net Examples . Through R4R you can develop ADO.Net programming concept. R4R provide ADO.Net Interview Questions with answers.R4R provide ADO.Net Languages study materials in easy way.

ADO.net Tutorials
1.1 ADO.NET Basic Tutorials(Examples)

ADO.net Interview Questions with Answers


3.1 3.2 3.3 3.4 ADO.net ADO.net ADO.net ADO.net Subjective Questions with Answers Interview Questions with Answers Objective Questions And Answers FAQs

Introduction of ADO .NET


Microsoft ADO.NET (ActiveX Data Objects .NET) is part of the Microsoft .NET Framework: a set of tools and layers that allows your application to easily manage and communicate with its file-based or server-based data store.ADO.NET (ActiveX Data Objects .NET) is the primary data access API for the .NET Framework. It provides the classes that you use as you develop database applications with Visual Basic .NET as well as other .NET languages. Ado.net consists of classes that allow a .NET application to connect to the data source, executes commands and manage disconnected data.In the .NET Framework, the ADO.NET libraries appear under the System.Data namespace.These libraries include functionality to connect to these data sources, execute commands,and store, manipulate, and retrieve data.

Various .NET Data Providers:-

ADO .NET Architecture

The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider, OLEDB Data Provider and ODBC Data Provider. SQL Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection Object respectively.

Data Provider he Data Provider is used for providing and maintaining the connection to the database. A DataProvider is a collection of related components that work together to provide data in an efficient and performance driven mannern.The .net framwork has two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes: The Connection object - It provides a connection to the database The Command object - It is used to execute a command The DataReader object- It provides a forward-only, read only, connected recordset The DataAdapter object- It populates a disconnected DataSet with data and performs update.

Data SET The dataset is a disconnected, in-memory representation of data. It can be defined as a local copy of the relevant portions of the database.DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. The DataTable is a collection of DataRow and DataCoulumn Object which contains Data. The DataAdapter Object create a bridge between the DataSet and the Data Source The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft sql database an oracle atabase or from a Microsoft Access database. ADO VS ADO .NET ADO ADO .NET ADO works with connected data. ADO.NET uses data in a disconnected fashion. In ADO, the in-memory representation of data In ADO.NET, it is the dataset is the recordset. In ADO.NET, rows are represented as collections, In ADO you scan sequentially through the so you can loop through a table as you would rows of the recordset using the ADO through any collection, MoveNext method. or access particular rows via ordinal or primary key index. ADO's are stateful(TCP/IP) ADO.NET's are stateless(internet) ADO objects communicate in binary mode. ADO.NET uses XML for passing the data. ADO allows you to create client-side cursors ADO.NET gives you the choice of either using only client-side or server-side cursors. Derives information about data implicitly at Leverages known metadata at design time in run time, based on metadata that is often order to provide better run-time performance expensive to obtain. and more consistent run-time behavior. ncludes implicit behaviors that may not ncludes implicit behaviors that may not always always be required in an application and that be required in an application and that may may therefore limit performance. therefore limit performance. Feature of ADO .NET The salient features of ADO.NET : Enhancements to the DataSet and Datatable classes Optimized DataSet Serialization Conversion of a DataReader to a DataSet or a DataTable and vice versa Data Paging Batch Updates Reduction in database roundtrips Asynchronous Data Access Common Provider Model

Bulk Copy

Advantage of ADO .NET 1. 2. 3. 4. 5. 6. ADO.NET Does Not Depend On Continuously Live Connections. Database Interactions Are Performed Using Data Commands. Data Can Be Cached in Datasets. Datasets Are Independent of Data Sources. Data Is Persisted as XML. Schemas Define Data Structure

ADO.NET basic Tutorials, ADO.NET basic Tutorials, ADO.NET basic tutorials with examples 1.

2. 3. Component classes 4. 5. 6. 7. 8.

Introduction of ADO .NET THE ADO.NET Architecture The SQLCOMMAND OBJECT Command Constructors The SQLCONNECTION OBJECT Handling Connection Events Dataset object in ADO .NET The steps involved to fill a dataset?

9. 10. Data adapter

11. Handling

DataAdapter Events 12. DataReader 13. Connecting to Various Data Sources


14. Use of CommandBuilder 15. ADO.NET

and XML 16. Transaction Processing in ADO.NET 17. Step To Create Transactions 18. Data Binding to Controls 19. Connection pooling 20. Using ADO.NET in Windows Forms 21. ADO Versus ADO.NET 22. Simple Data Binding in Windows Forms

23. Complex Data Binding in Windows Forms 24. Displaying Hierarchical Data Using the DataGrid 25. Display Data Using the DataGridview and oledbconnection 26. Display Data Using the DataGridview and Sqlconnection 27. DataView Object 28. Displaying the Row States 29. Moving Large Amounts of Data Using SqlBulkCopy 30. Editing Disconnected Data 31. Copy a DataTable 32. DataTable Events 33. Usage of DataTable Events 34. Merge Two Table 35. Same Table Structures, with Primary Key 36. Merge Case : Same Table Structures,No Primary Key 37. Merge Case : Common Column, with Primary Key 38. Merge Case : Absolutely Different Table Structures 39. Adding Records Using Mapped Names 40. Updating Records Using Mapped Names 41. Working with Stored Procedures 42. Stored Procedures Comparison with functions 43. Stored Procedures Example 44. Using ADO.NET in Web Forms 45. Using the DataList Control 46. COM Interoperability 47. Using ADOX in the .NET Framework 48. Connecting to MS Access Database in ASP .NET 49. Read Data from table using OleDBDataReader 50. Connecting to MS SQL Database in ASP .NET 51. How To Update a Grid View Value Using Procedure in ASP .NET 52. Insert a Data in Database using Procedure in ASP .NET 53. How to Get all Information SQL Server in ASP .NET 54. Retrieving Data Using a SQL Server Stored Procedure IN ASP.NET 55. Build SqlConnectionStringBuilder from connection string 56. How To Build a connection string from component parameters and display It. 57. Executing a Parameterized Query with SqlCommand in ASP. NET 58. How to execute multiple SQL statements using a SqlCommand object 59. How to Get Table Information in ASP .NET 60. How to update a table data in GridView Control Using C# 61. Inserts (Create) a new table in ASP .Net using C# 62. Insert Data using SqlCommandBuilder in ADO.NET using C# 63. Using SqlCommandBuilder show SQL statement

Introduction of ADO .NET

ADO stands for ActiveX Data Object .ADO.NET is an object-oriented set of libraries that allows to interact with data sources. The data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file.ADO .NET consists of classes that allow a .NET application to connect to the data source, executes commands and manage disconnected data. One of the key Differences between ADO.NET and other database technologies is how it deals with Challenge with different data sources, that means, the code you use to connect to an SQL Database will not differ that much to the one connecting to an Oracle Database. ADO.NET is Microsoft's platform for data access in its new .NET Framework. It is scalable, interoperable, and familiar enough to ADO developers to be immediately usable and By design, the ADO.NET object model and many of the ADO.NET code constructs will look very familiar to ADO developers. Benefits of ADO.NET ? ADO.NET offers numerous advantages compared to its previous versions of ADO and other data access components. 1. Interoperability- The ability to communicate across heterogeneous environment. 2. Maintainability- Various substantial, architectural changes and transformations required in the life of a deployed system can be easily carried out, if the application is implemented in ADO.NET using datasets. 3. Programmability- ADO.NET data components enables you program more quickly and with fewer mistakes in Visual Studio encapsulate data access functionality. It also allows you to access data through typed programming as ADO.NET data classes generated by the designer tools result in the typed datasets. 4. Performance- ADO.NET datasets offer performance advantages, for disconnected applications, over ADO disconnected record sets. 5. Scalability- ADO.NET enables scalability by helping the programmers to conserve limited resources. 6.Productivity-The ability to quickly develop robust data access applications using ADO .NET's rich and extensible component object model. THE ADO.NET NAMESPACES ADO .NET has several namespaces containing classes that represent database objects such as connections, commands, and datasets. Perhaps the most important of these classes is the new XML-enabled DataSet which provides a relational data store and astandard API independent of any underlying database management system. .NET Framework Namespaces Involved in Data Access:NAMESPACE DESCRIPTION

Provides base classes for ADO.NET, focused on the DataSet class and its child classes, such as DataRow, DataColumn, and DataRelation. System.Data.SqlClient The SQL Server .NET data provider. System.Data.OleDb The OLE DB .NET data provider. Provides classes that are shared by all .NET data providers. Many of System.Data.Common these classes are abstract and may be used to create custom data providers. System.Data.SqlTypes Provides classes for native data types in SQL Server. System.Xml Provides classes for processing XML. Provides classes for processing XML Schema Definition (XSD) schema System.Xml.Schema files. Provides classes for processing Extensible Stylesheet Transformation System.Xml.Xsl (XSLT) transforms. System.Data There are two managed providers:1-The Oledb 2-Sql server The OLE DB and SQL Server managed providers DataSet provides a stand-alone entity separate from the underlying store, in most cases it will get its data from a managed provider whose role is to connect, fill, and persist the DataSet to and from a data store. .NET offers two such providers embodied in the following two namespaces: System.Data.SqlClientUsed to talk directly to Microsoft SQL Server. System.Data.OleDbUsed to talk to any other provider that supports OLE DB (a COMbased API for accessing data).

THE ADO.NET Architecture?


Data Access in ADO.NET relies on two components: DataSet and Data Provider. DataSet The dataset is a disconnected storage and disconnected in-memory representation of data. It can be used as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database. Data Provider

The Data Provider is responsible for maintaining and providing the connection to the database. A DataProvider is a set of related components that work together to provide data in an efficient and performance driven manner. The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like Access and Oracle. Each DataProvider consists of the following component classes: The Connection :-TheConnection object which provides a connection to the database The Command :-The Command object which is used to execute a command The DataReader:- The DataReader object which provides a forward-only, read only, connected recordset The DataAdapter :-The DataAdapter object which populates a disconnected DataSet with data and performs update A connection object create the connection for the application with the database. The command object provides direct execution of the command to the database. If the command returns more than a single value, the command object returns a DataReader to provide the data. Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated using the command object or the DataAdapter.

Component classes
1-The Connection Object The Connection object creates the connection to the database. Microsoft Visual Studio .NET provides two types of Connection classes first is the SqlConnection object, which is designed specifically to connect to Microsoft SQL Server 7.0 or later, and the other is OleDbConnection object, it can provide connections to a wide range of database types like Microsoft Access and Oracle. The Connection object contains all of the information required to open a connection to the database. 2-The Command Object It is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute commands to a database across a data connection. Command objects can be used to execute stored procedures on the database, SQL

commands, and return complete tables directly. It provide three methods which are used to execute commands on the database: (i)-ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE (ii)ExecuteScalar: Returns a single value from a database query (iii)ExecuteReader: Returns a result set by way of a DataReader object 3-The DataReader Object The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data Provider, DataReader objects cannot be directly instantiated.The DataReader is returned as the result of the Command object's ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when we do not need to keep the data cached in memory because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader. 4:-The DataAdapter Object The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is used to fill a DataTable or DataSet with data from the database with it's Fill method. After the memory-resident data has been manipulated.Tthe DataAdapter can commit the changes to the database by calling the Update method. The DataAdapter provides four properties that represent database commands: (i) Select Command (ii) Insert Command (iii) Delete Command (iv) Update Command When the Update method is called, changes in the DataSet are copied back to the database and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed. Define connected and disconnected data access in ADO.NET connected data access in ADO.NET :-Data reader is based on the connected architecture for data access. Does not allow data manipulation Disconnected data access in ADO.NET:-Dataset supports disconnected data access architecture. This gives better performance results. Describe CommandType property of a SQLCommand in ADO.NET. CommandType property:-CommandType property is a property of Command object that can be set to Text, Storedprocedure. If it is Text, the command executes the database query. When it is StoredProcedure, the command runs the stored procedure. A SqlCommand is an object that allows specifying what is to be performed in the database.

Access database at runtime using ADO.NET Access database at runtime using Sqlconnection in ADO.NET

Using System.Data.SqlClient; SqlConnection con = new SqlConnection(connectionString) con.Open(); string stringQuery = "select EmployeeName from emp"; SqlCommand cmd = new SqlCommand(stringQuery, con); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Console.WriteLine(dr [0]); } dr.Close(); con.Close();

The Connection String in the App.Config File

<connectionStrings> <add name="DragDropWinApp.Settings.TestConnectionString" connectionString= "Data Source=(local);Initial Catalog=emp;Integrated Security=True" providerName="System.Data.SqlClient" />

The SQLCOMMAND OBJECT


When we have a more complex query that retrieves records from different tables, or don't want the UPDATE command to check for changes in the database before updating it, we can specify our own SQL commands.The Command object enables to execute queries against data source. in order to retrieve data, you must know the schema of your database as well as how to build a valid SQL query. The Command objects allow developers to specify parameters dynamically at run time. When defining the SQL statement we use a placeholder instead of a particular value. Then we use the Parameters collection of the Command object to define the dynamic column value.The SqlCommand object must be used in conjunction with the SqlConnection object Creating a SqlCommand Object

SqlCommand cmd = new SqlCommand("select CategoryName from Categories", new sqlconnection(parameter)); Querying Data using a SQL select command 1)Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand("select EmployeeName from Emp", conn); 2. Call Execute reader to get query results SqlDataReader dr = cmd.ExecuteReader(); Inserting Data using a SQL insert command,To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object. 1)Insert command string string insertString = @" insert into Emp (EmpName, Post) values ('Aditya', 'S\w Engg')"; 2.)Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand(insertString, conn); 3) Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Updating Data using a SQL update command,To update data into a database, use the ExecuteNonQuery method of the SqlCommand object. 1)prepare command string string updateString = @" update Emp set EmpName = 'Ashish' where CategoryName = 'Raj'"; 2) Instantiate a new command with command text only SqlCommand cmd = new SqlCommand(updateString,conn); 3) Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Deleting Data

using a SQL delete command,To delete data into a database, use the ExecuteNonQuery method of the SqlCommand object. 1) delete command string string deleteString = @" delete from Emp where EmpName = 'Ashish'"; 2) Instantiate a new command SqlCommand cmd = new SqlCommand(); 3) Set the CommandText property cmd.CommandText = deleteString; 4) Set the Connection property cmd.Connection = conn; 5)Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Getting Single Values For getting a single value we can use count, sum, average, or other aggregated value from a data set. 1) Instantiate a new command SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn); 2) Call ExecuteNonQuery to send command int count = (int)cmd.ExecuteScalar();

Command Constructors
New(): Creates a new, default instance of the Data Command New(Command): Creates anew Data Command with the Command Text set to the string specified in command. New(Command, Connection): Creates a new Data Command with the Command Text set to the string specified in Command and the Connection property set to the SqlConnection specified inConnection New(Command, Connection, Transaction): Creates anew Data Command with the CommandText set to the string specified in Command the Connection property set to the Connection specified in Connection,and the Transactionproperty set to the transaction specified in Transaction.

Example of SqlCommand Object

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

class SqlCommandexample { SqlConnection conn; public SqlCommandDemo() { // Instantiate the connection conn = new SqlConnection( "Data Source=computer;Initial Catalog=Emp;Integrated Security=SSPI"); } // call methods that demo SqlCommand capabilities static void Main() { SqlCommandexample scd = new SqlCommandexampleo(); Console.WriteLine(); Console.WriteLine("Categories Before Insert"); Console.WriteLine("-----------------------"); // use ExecuteReader method scd.ReadData(); // use ExecuteNonQuery method for Insert scd.Insertdata(); Console.WriteLine(); Console.WriteLine("Categories After Insert"); Console.WriteLine("-----------------------------"); scd.ReadData(); // use ExecuteNonQuery method for Update scd.UpdateData(); Console.WriteLine(); Console.WriteLine("Categories After Update"); Console.WriteLine("-----------------------------"); scd.ReadData();

// use ExecuteNonQuery method for Delete scd.DeleteData(); Console.WriteLine(); Console.WriteLine("Categories After Delete"); Console.WriteLine("-----------------------------"); scd.ReadData(); // use ExecuteScalar method int numberOfRecords = scd.GetNumberOfRecords(); Console.WriteLine(); Console.WriteLine("Number of Records: {0}", numberOfRecords); } /// <summary> /// use ExecuteReader method /// </summary> public void ReadData() { SqlDataReader rdr = null; try { // Open the connection conn.Open(); // 1. Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand("select EmpName from Emp", conn); // 2. Call Execute reader to get query results rdr = cmd.ExecuteReader(); // print the CategoryName of each record while (rdr.Read()) { Console.WriteLine(rdr[0]); } } finally

// close the reader if (rdr != null) { rdr.Close(); } // Close the connection if (conn != null) { conn.Close(); }

/// <summary> /// use ExecuteNonQuery method for Insert /// </summary> public void Insertdata() { try { // Open the connection conn.Open(); // prepare command string string insertString = @" insert into Emp (EmpName, post) values ('Raj', 'A\c')"; // 1. Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand(insertString, conn); // 2. Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); } finally { // Close the connection if (conn != null) { conn.Close(); } } } /// <summary>

/// use ExecuteNonQuery method for Update /// </summary> public void UpdateData() { try { // Open the connection conn.Open(); // prepare command string string updateString = @" updateEmp set EmpName = 'Anil' where EmpName = 'Raj'"; // 1. Instantiate a new command with command text only SqlCommand cmd = new SqlCommand(updateString); // 2. Set the Connection property cmd.Connection = conn;

// 3. Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); } finally { // Close the connection if (conn != null) { conn.Close(); } } } /// <summary> /// use ExecuteNonQuery method for Delete /// </summary> public void DeleteData() { try { // Open the connection conn.Open(); // prepare command string string deleteString = @"

delete from Emp where EmpName = 'Ashish'"; // 1. Instantiate a new command SqlCommand cmd = new SqlCommand(); // 2. Set the CommandText property cmd.CommandText = deleteString; property // 3. Set the Connection cmd.Connection = conn; // 4. Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); } finally { // Close the connection if (conn != null) { conn.Close(); } } } /// <summary> /// use ExecuteScalar method /// </summary> /// <returns>number of records</returns> public int GetNumberOfRecords() { int count = -1; try { // Open the connection conn.Open(); // 1. Instantiate a new command SqlCommand cmd = new SqlCommand("select count(*) from Emp", conn);

// 2. Call ExecuteScalar to send command count = (int)cmd.ExecuteScalar(); } finally { // Close the connection if (conn != null) { conn.Close(); } } return count; } }

The SQLCONNECTION OBJECT


A SqlConnection is an object,as any other C# object. we just declare and instantiate the SqlConnection all at the same time, as shown below: SqlConnection con = new SqlConnection( "Data Source=(local);Initial Catalog=Emp;Integrated Security=sspi"); The SqlConnection object instantiated above by using a constructor with a single argument of type string and this argument is called a connection string. There are four Connection String Parameter Name:1)Data Source: Data Source Identifies the server and it Could be local machine, machine domain name, or IP Address. 2)Initial Catalog: Database name 3)Integrated Security: Integrated Security set to SSPI to make connection with user's Windows login. 4)User ID: Name of user configured in SQL Server. 5)Password: Password matching SQL Server User ID. The following shows a connection string, using the User ID and Password parameters: SqlConnection conn = new SqlConnection( "Data Source=DatabaseServer;Initial Catalog=Northwind;User ID=YourUserID;Password=YourPassword");

Using a SqlConnection The aim of creating a SqlConnection object is so we can enable other ADO.NET code to work with a database and SqlCommand and a SqlDataAdapter take it a connection object as a parameter. The sequence of operations occurring in the lifetime of a SqlConnection are given below: 1. 2. 3. 4. 5. Instantiate the SqlConnection. Open the connection. Pass the connection to other ADO.NET objects. Perform database operations with the other ADO.NET objects. Close the connection.

The Open() Method: The Open() method of the Connection object establishes a connection to the data source.,because database connections are a very expensive resource memory-wise, so we should only call the Open() method just before we're ready to retrieve the data. This ensures that the connection is not open any longer than it needs to be. The Close() Method After we are done retrieving data,we should call the Close() method of the Connection object. This closes the connection to the database. Example Using SQLCONNECTION Object

using System; using System.Data; using System.Data.SqlClient; class sqlConnectivityexample { static void Main() { SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Emp;Integrated Security=SSPI"); SqlDataReader rdr = null; try { // 2. Open the connection conn.Open(); // 3. Pass the connection to a command object SqlCommand cmd = new SqlCommand("select * from emp", conn); //

// 4. Use the connection // // get query results rdr = cmd.ExecuteReader(); // print the CustomerID of each record while (rdr.Read()) { Console.WriteLine(rdr[0]); }

} finally { // close the reader if (rdr != null) { rdr.Close(); }

} } }

// 5. Close the connection if (conn != null) { conn.Close(); }

Handling Connection Events


Both the OLE DB and the SQL Server Connection objects provide two events: 1)StateChange 2)InfoMessage. 1)StateChange the StateChange event fires whenever the state of the Connection object changes. The event passes a StateChangeEventArgs to its handler, which, inturn, has two properties: OriginalState and CurrentState. The possible values for OriginalState and CurrentState are: Connection States Broken Meaning TheConnecton is open, but not functional. It maybe closed and reopened

Closed Connecting Executing Fetching

The Connection is closed The Connection is in the process of connecting, but has not yet been

Executing the command

Open

Retrieving the data Open the connection

To display the previous and current Connection states for each of the two Connection objects: Select OleDbConnection1 in the Class Name combobox of the editor and the StateChange event in the Method Name combobox.

private void oleDbConnection1_StateChange (object sender,StateChangeEventArgs e) { string s; s = "The Connection State is changing from " + e.OriginalState.ToString() + " to " + e.CurrentState.ToString(); MessageBox.Show(s); } private void SqlDbConnection1_StateChange (object sender, StateChangeEventArgs e) { string s1; s1 = "The Connection State is changing from " + e.OriginalState.ToString() + " to " + e.CurrentState.ToString(); MessageBox.Show(s1); }

Add the code to connect the event handlers to the:ConnectionProperties sub: this.oleDbConnection1.StateChange += newSystem.Data.StateChangeEventHandler(this.oleDbConnection1_StateChange); this.SqlDbConnection1.StateChange += new System.Data.StateChangeEventHandler(this.SqlDbConnection1_StateChange); . Save and run the program. Change the Connection Type and then click the Test button.

The application displays two MessageBoxes as the Connection is opened and closed. 2)InfoMessage The InfoMessage event is triggered when the data source returns warnings. The information passed to the event handler depends on the Data Provider.

Dataset object in ADO .NET


The DataSet object is a disconnected storage.DataSet is a disconnected in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. It represents related tables, constraints, and relationships among the tables. DataSet reads and writes data and schema as XML documents.The DataSet object is a disconnected storage.It is used for manipulation of relational data. The DataSet is filled with data from the storeWe fill it with data fetched from the data store. Once the work is done with the dataset, connection is reestablished and the changes are reflected back into the store.

ADO.NET DataSet can contain more than one table and also contains information about table relationships, the columns they contain, and any constraints that apply. Each table in a DataSet can contain multiple rows. Once data is retrieved from the database into a DataSet object, an application can disconnect from the database before processing the DataSet. This is an important feature of the ADO.NET DataSet. It gives us an in-memory, disconnected copy of a portion of the database which we can process without retaining an active connection to the database server.

Creating and using a DataSet The typical steps in creating and using a DataSet are: (i)Create a DataSet object (ii) Connect to a database (iii)Fill the DataSet with one or more tables or views (iv)Disconnect from the database (v)Use the DataSet in the application

Example of DataSet

using System; using System.Data; using System.Data.SqlClient; public class empcount { public static void Main() { // change the following connection string, as necessary... string con = @"server=(local)\kamal;database=Emp;trusted_connection=yes"; DataSet ds = new DataSet("EmpDataSet"); SqlDataAdapter sad; string sl; sl = "SELECT COUNT(*) AS cnt FROM employee"; sad = new SqlDataAdapter(sl, con); sad.Fill(ds, "emp_count"); sl = "SELECT COUNT(*) AS cnt FROM compocation"; sad = new SqlDataAdapter(sl, con); sad.Fill(ds, "comploc_count");

int totalemp = (int) ds.Tables["emp_count"].Rows[0]["cnt"]; int comploc = (int) ds.Tables["comploc_count"].Rows[0]["cnt"]; Console.WriteLine( "There are {0} employee, {1} complocation .", totalemp , comploc, ); } }

The steps involved to fill a dataset?


There are following steps to fill a dataset:(i). Create a connection object. (ii). Create an adapter by passing the string query and the connection object as parameters. {iii). Create a new object of dataset. (iv). Call the Fill method of the adapter and pass the dataset object. We can check that some changes have been made to dataset since it was loaded? There are following way to check that some changes have been made to dataset since it was loaded:(i). GetChanges: gives the dataset that has changed since newly loaded or since Accept changes has been executed. {ii}. HasChanges: this returns a status that tells if any changes have been made to the dataset since accept changes was executed. How can we add/remove rows in DataTable object of DataSet? Using NewRow method we can add row's in a data table object of dataset.Remove method of the DataRowCollection is used to remove a DataRow object from DataTable. RemoveAt method of the DataRowCollection is used to remove a DataRow object from DataTable per the index specified in the DataTable. UPDATING THE DATABASE USING A DATASET The underlying database can be updated directly by passing SQL INSERT/UPDATE/ DELETE statements, or stored procedure calls, through to the managed provider. It We can also be updated using a DataSet. The steps are: 1. Create and fill the DataSet with one or more DataTables 2. Call DataRow.BeginEdit on a DataRow 3. Make changes to the rows data

4. Call DataRow.EndEdit 5. Call SqlDataAdapter.Update to update the underlying database 6. Call DataSet.AcceptChanges (or DataTable.AcceptChanges orDataRow.AcceptChanges) Example :-UPDATING THE DATABASE USING A DATASET To update the database directly, we can use the SqlCommand object, which allows us to execute SQL INSERT, UPDATE, and DELETE statements against a database.

Using System; using System.Data; using System.Data.SqlClient; public class empdel { public static void Main() { SqlConnection con = new SqlConnection( @"server=(local)\computer;database=emp;trusted_connection=yes" ); string sql = "DELETE FROM emp WHERE emp_name = 'Ashok'"; SqlCommand cmd = new SqlCommand(sql, con); con.Open(); int i = cmd.ExecuteNonQuery(); con.Close(); Console.WriteLine("{0} record(s) deleted.", i); } }

To load multiple tables in a DataSet

DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter ("Emp", this.Connection); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.AddWithValue ("@EId", EId); da.TableMappings.Add ("Table", ds.xval.TableName); da.Fill (ds);

ADO.NET Code showing Dataset storing multiple tables.

DataSet ds = new DataSet(); ds.Tables.Add(dt1);

ds.Tables.Add(dt2); ds.Tables.Add(dt3); ds.Tables.Add(dt4); ds.Tables.Add(dt5); .................. ................. .................. ds.Tables.Add(dtn);;

The use of data adapter.?


data adapter:-The DataAdapter serve as a bridge between a DataSet and data source for retrieving and saving data. The DataAdapter provides this bridge by using Fill to load data from the data source into the DataSet and using Update to send changes made in the DataSet back to the data source. The data adapter objects connect a command objects to a Dataset object. They provide the means for the exchange of data between the data store and the tables in the DataSet.An OleDbDataAdapter object is used with an OLE-DB provider A SqlDataAdapter object uses Tabular Data Services with MS SQL Server. Namespace: System.Data.Common Assembly: System.Data (in System.Data.dll) Data adapter Flow Architecture The DataAdapter acts as a bridge between the disconnected DataSet and the data source. It exposes two interfaces; the first of these,IDataAdapter that defines methods for populating a DataSet with data from the data source and for updating the data source with changes made to the DataSet on the client. The another interface is IDbDataAdapter that defines four properties, each of type IDbCommand. These all properties each set or return a command object specifying the command to be executed when the data source is to be queried or updated:

Constructors of Data Adapter?

There are two constructor:


Name Description Initializes a new instance of a DataAdapter class from an existing object of the same type. Initializes a new instance of a DataAdapter class.

DataAdapter(DataAdapter)

DataAdapter

Property of Data Adapter? there are following main property: Name Description

TableMappings

Gets a collection that provides the master mapping between a source table and a DataTable. Gets the IContainer that contains the Component. (Inherited from Component.) Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets or sets whether AcceptChanges is called during a Update. Gets or sets a value indicating whether AcceptChanges is called on a DataRow after it is added to the DataTable during any of the Fill operations.

Container

DesignMode

Events

AcceptChangesDuringUpdate

AcceptChangesDuringFill

Method of Data Adapter? there are following main method:Description Releases all resources used by the Component (Inherited fromComponent.) Adds or refreshes rows in the DataSet to match those in the data source. Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Name

Dispose

Fill(DataSet)

Finalize

GetHashCode

GetType

Event of Data Adapter? There are two events:Name Description Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.) Returned when an error occurs during a fill operation.

Disposed

FillError

Interface Implementation of Data Adapter? Name IDataAdapter.TableMappings Description Indicates how a source table is mapped to a dataset table.

Basic method of Data Adapter? There are three basic method in data adopter:(i)Fill:-Fill method executes the SelectCommand to fill the DataSet object with data from the data source,Depending on whether there is a primary key in the DataSet, the fill can also be used to update an existing table in a DataSet with changes made to the data in the original datasource. (ii)FillSchema:-Fill Schema method executes the SelectCommand to extract the schema of a table from the data source and creates an empty table in the DataSet object with all the corresponding constraints. (iii0Update:-Update method executes the InsertCommand, UpdateCommand, or DeleteCommand to update the original data source with the changes made to the content of the DataSet. (iv) Dispose :- releases all the resources

Handling DataAdapter Events


DataAdapter supports only two events:

OnRowUpdating and OnRowUpdated. T hese two events occur on either side of the actual dataset update, providing fine control of the process. 1)OnRowUpdating Event The OnRowUpdating event is raised after the Update method has set the parameter values of the command to be executed but before the command is executed. The event handler for this event receives an argument whose properties provide essential information about the command that is about to be executed. The class of the event arguments is defined by the Data Provider, so it will be either OleDbRowUpdatingEventArgs or SqlRowUpdatingEventArgs if one of the .NET Framework Data Providers is used. RowUpdatingEventArgs Properties Command:- The Data Command to be executed. Errors:-The errors generated by the .NET Data Provider Row:-The DataReader

to be updated

StatementType:-The type of Command tobe executed.The possiblevalues are Select, Insert Delete, and Update
Status:-The UpdateStatus

of the Command ping used by the update

TableMapping:-The DataTableMap 2)OnRowUpdated Event

The OnRowUpdated event is raised after the Update method executes the appropriate command against the data source. The event handler for this event is either passed an SqlRowUpdatedEventArgs or an OleDbRowUpdatedEventArgs argument, depending on the Data Provider. Example:-

// Assumes that connection is a valid SqlConnection object. SqlDataAdapter sda = new SqlDataAdapter(

"SELECT EmpID, EmpName FROM Emp", connection); // Add handlers. sda.RowUpdating += new SqlRowUpdatingEventHandler(OnRowUpdating); sda.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); // Set DataAdapter command properties, fill DataSet, modify DataSet. sda.Update(ds, "Emp"); // Remove handlers. sda.RowUpdating -= new SqlRowUpdatingEventHandler(OnRowUpdating); sda.RowUpdated -= new SqlRowUpdatedEventHandler(OnRowUpdated); protected static void OnRowUpdating( object sender, SqlRowUpdatingEventArgs args) { if (args.StatementType == StatementType.Delete) { System.IO.TextWriter tw = System.IO.File.AppendText("Deletes.log"); tw.WriteLine( "{0}: Customer {1} Deleted.", DateTime.Now, args.Row["EmpID", DataRowVersion.Original]); tw.Close(); } } protected static void OnRowUpdated( object sender, SqlRowUpdatedEventArgs args) { if (args.Status == UpdateStatus.ErrorsOccurred) { args.Row.RowError = args.Errors.Message; args.Status = UpdateStatus.SkipCurrentRow; } }

DataReader

The DataReader provides a read-only, forward-only stream of results from a database query or stored procedure and we can use a DataReader if it is desirable,and possible, to keep the connection to the database open while data is being processed.A DataReader is a lightweight object which provides read-only, forward-only data in a very fast and efficient way . DataReader is efficient than using a DataAdapter but it is limited and Data access with DataReader is read-only, i.e, you cannot make any changes (update) to data and forward-only, i.e we cannot go back to the previous record which was accessed. DataReader requires the exclusive use of an active connection for the entire time if it is in existence and we instantiate a DataReader by calling a Command object's ExecuteReader command. When the DataReader is first returned it is positioned before the first record of the result set. To making the first record available we need to call the Read method and If a record is exist, the Read method moves the DataReader for next record and returns True and If a record is not available then the Read method returns False. we can use a While Loop to iterate through the records with the Read method. Example of DataReader

using System; using System.Data; using System.Data.SqlClient; public class empnamereader { public static void Main() { SqlConnection con = new SqlConnection( @"server=(local)\mycomputer;database=emp;trusted_connection=yes" ); string s = "SELECT * FROM emp"; con.Open(); sqlcommand cmd=new sqlcommand(s, con); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Console.WriteLine(sdr["empname"] ); } con.Close(); } } Data Retrieval Methods of the DataReader Object

Method
GetBoolean() GetByte() GetChar() GetDateTime() GetDecimal() GetDouble() GetFloat()

Field Type
Bool Byte Char DateTime Decimal Double Float

GetGuid() GetInt16() GetInt32() GetInt64() GetString()

Guid Int16 Int32 Int64 String

Differences between DataSet and DataReader. DataSet DataReader DataSet object can contain multiple rowsets from the same data source as well as from DataReader provides forward-only and readthe relationships between them. only access to data. Dataset is a disconnected architecture. Dataset can persist data. Datareader is connected architecture. Datareader can not persist data.

A DataSet is well suited for data that needs It has live connection while reading data to be retrieved from multiple tables. DatsSet is slower than DataReader ,Due to overhead. Speed performance is better in DataReader

Limitations of the DataReader There is not possible to sort, filter, or manipulate the data while using a DataReader, since it is read-only and forward-only.

Connecting to Various Data Sources


There are following way to connect to a Microsoft SQL database and open and close a connection: 1)Connecting to SQL Server in C#:

SqlConnection conn = new SqlConnection("Initial Catalog=computer;Server=(local);UID=sa;PWD="); conn.Open(); conn.Close();

There are following way to connect to a Microsoft Jet OLE DB provider. and open and close a connection:-

1)Connecting to a Microsoft Access Database in C#

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=c:\\emp.mdb;" + "User Id=admin;" + "Password=;" ); conn.Open(); conn.Close();

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=c:\\emp.mdb;" + "User Id=admin;" + "Password=;" ); conn.Open(); conn.Close(); 2)Connecting to a Microsoft Access Database in Visual Basic .NET

Dim conn as OleDbConnection = New OleDbConnection( _ "Provider=Microsoft .Jet.OLEDB.4.0;" + _ "Data Source=c:\Emp.mdb;" + _ "User Id=admin;" +_ "Password=;" ) conn.Open() conn.Close()

3)Connecting to an Oracle Database in C#

OleDbConnection conn = new OleDbConnection( _ "Provider=OraOLE DB.Oracle" + _ "Data Source=DataBasename" + _ "User Id=username;" + _ "Password=passwo rd;" ); conn.Open(); conn.Close();

4) Connecting to an Oracle Database in Visual Basic .NET

Dim conn as OleDbConnection = New OleDbConnection( _ "Provider=OraOLE DB.Oracle" + _ "Data Source=DataBasename" + _ "User Id=username;" + _ "Password=passw ord;" ) conn.Open() conn.Close()

Use of CommandBuilder
CommandBuilder builds Parameter objects automatically and SqlCommandBuilder object to automatically create the DeleteCommand, the InsertCommand, and the UpdateCommand properties of the SqlCommand object for a SqlDataAdapter object, Insert Data using SqlCommandBuilder

using System; using System.Data; using System.Data.SqlClient; class stringbuildinginsert { static void Main(string[] args) { SqlConnection con = new SqlConnection("server=(local)\\SQLEXPRESS;database=Emp;Integrated Security=SSPI;"); SqlDataAdapter sda = new SqlDataAdapter("SELECT ID, FirstName, LastName FROM Employee", con); SqlCommandBuilder Cmdb = new SqlCommandBuilder(sda); DataSet ds = new DataSet(); sda.Fill(ds); DataRow drow = ds.Tables[0].NewRow(); drow["ID"] = 200; drow["FirstName"] = "Kamal"; drow["LastName"] = "Mishra"; ds.Tables[0].Rows.Add(MyRow);

} }

sda.Update(ds);

Delete Data using SqlCommandBuilder

using System; using System.Data; using System.Data.SqlClient; class stringbuildinginsert { static void Main(string[] args) { SqlConnection con = new SqlConnection("server=(local)\\SQLEXPRESS;database=Emp;Integrated Security=SSPI;"); SqlDataAdapter sda = new SqlDataAdapter("SELECT ID, FirstName, LastName FROM Employee", con); SqlCommandBuilder Cmdb = new SqlCommandBuilder(sda); DataSet ds = new DataSet(); sda.Fill(ds); DataColumn[] dc = new DataColumn[1]; dc[0] = ds.Tables[0].Columns[0]; dst.Tables[0].PrimaryKey = dc; DataRow drow = MyDataSet.Tables[0].Rows.Find(1); drow.Delete(); sdar.Update(ds);

} }

ADO.NET and XML


XML stands for EXtensible Markup Language.XML was designed to carry data, not to display data and XML tags are not predefined,we must define your own tags.XML is designed to be self-descriptive and XML is a W3C Recommendation.XML is a markup language that can be used to represent complicated data in a hierarchical format.The format of the generated XML document is far more readable than the ADO equivalent the columns are represented by elements, not attributes, and there aren't a lot of unnecessary XML namespaces: XML Parser

An XML parser is a program that extracts the data and data descriptions and reads XML document from the XML data And it enables to programmatically work with an XML document without having to manually parse the file. The format of the generated XML document is far more readable than the ADO equivalent the columns are represented by elements, not attributes, and there aren't a lot of unnecessary XML namespaces: A Example of XML Document

<?xml version="1.0"> <customer type="web"> <firstName>Kamal</firstName > <lastName>Mishra</lastName > <address>Ashok nagar Delhi </address> <city>New Delhi</city> <zip>101100</zip> </customer>

We can load any well-formed XML document into a DataSet, without having to use a predefined structure (although we might lose content if the structure of the document is not basically tabular).

// Store the XML document in a string string xmlDoc = @"<?xml version='1.0'?> <books> <book> <title>xml and ado .net</title> <publisher>R4R</publisher> </book> </books>"; // Load this into a StringReader StringReader sr = new StringReader(xmlDoc); // Create a new DataSet and read in the XML DataSet ds = new DataSet(); ds.ReadXml(sr);

// Display the column names and row data as a table foreach (DataColumn dc in ds.Tables[0].Columns) { Console.Write("{0,-15}", dc.ColumnName); } Console.Write("\n"); foreach (DataRow dr in ds.Tables[0].Rows) { Console.WriteLine("{0,-15} {1,-15}", dr[0], dr[1]); }

Creating a DataSet from an XML File The DataSet object has an overloaded method named ReadXml() that enables you to read XML data from a string, stream, or file. dataSet.ReadXml("file.xml"); ReadXml()Method ReadXml() is used to perform the magic of locating and loading the XML file. Readxml() is a very robust method, and used with different way depending on what objects we pass ReadXml(), it will perform different actions: ReadXml( XmlReader reader, XmlReadMode mode ) When we are passing an XmlReader as the first argument, ReadXml() will read data from an XmlReader object. ReadXml( Stream stream, XmlReadMode Mode )When we are passing a stream as the first argument, ReadXml() will read data from a stream. ReadXml( String fileName, XmlReadMode Mode ) When we are passing a filename to ReadXml(), it will retrieve XML from a file.

XmlReadMode Options for Retrieving XML Code Auto ReadSchema IgnoreSchema InferSchema DiffGram Fragment Symbol ReadXml() automatically select XmlReadMode by examining the XML document. ReadXml() reads XML schema and loads both data and schema into DataSet. ReadXml()completely ignores XML schema and try to load data into DataSet using existing DataSet schema. ReadXml()ignores explicit schema information in the XML using the structure of the XML data as the schema. ReadXml()will read the XML as a DiffGram, appending and merging rows as needed. ReadXml()will read the document as partial XML and import the data matching the

DataSet schema and ignore the rest. Serialization Serialization is defined as a way of saving the state of an object. In Microsoft .NET, serialization refers to the conversion of an object's values into XML. Deserialization normally refers to the reverse process of building an object based on saved values in an XML document. Viewing the Contents of a DataSet The GetXml() method of the DataSet object is used that return the DataSet's contents in XML form as a string. First, a table of information is retrieved from the table in database. Then it is placed into a label Web control in a Web form in order to display it. EXAMPLE:-

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <HTML> <HEAD> <script language="c#" runat="server" > void Page_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Data Source=compee;Initial Catalog=Emp;Integrated Security=sspi"); SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn) SqlDataAdapter adapt= new SqlDataAdapter(cmd) DataSet dsCustomers = new DataSet() conn.Open() adapt.Fill(dsCustomers, "Customers") conn.Close() lblOutput.Text = dsCustomers.GetXml()

} </script> </HEAD> <body> <form runat="server"> XML Output:<br> <asp:label id="lblOutput" runat="server"/> </form> </body> </html>

Writing a DataSet to an XML File WriteXml().method is used to writing a dataset to an xml file. There are three different XmlWriteModes: Code Description

IgnoreSchema Writes the DataSet as XML without any additional schema information. WriteSchema Writes the DataSet as XML with additional schema information included as inline XSD schema. DiffGram Writes the DataSet as a DiffGram.

DiffGram : A DiffGram is an XML document that is used to store original and current values for the data in a DataSet. EXAMPLE

void Page_Load(object sender, EventArgs e) {

SqlConnection conn = new SqlConnection("Data Source=compee;Initial Catalog=Emp;Integrated Security=sspi"); SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn) SqlDataAdapter adapt= new SqlDataAdapter(cmd) DataSet dsCustomers = new DataSet() conn.Open() adapt.Fill(dsCustomers, "Customers") conn.Close() dsCustomers.WriteXml(Server.MapPath("XMLFiles/MyXMLFile.xml ")); }

Transaction Processing in ADO.NET


ADO.NET supports transactions through the Transaction object, which is created against an open connection. Commands that are executed against the connection while the transaction is pending must be enrolled in the transaction by assigning a reference to the Transaction object to their Transaction property. Commands cannot be executed against the Connection outside the transaction while it is pending. If the transaction is committed, all of the commands that form a part of that transaction will be permanently written to the data source. If the transaction is rolled back, all of the commands will be discarded at the data source. Creating Transactions The Transaction object is implemented as part of the data provider. There is a version for each of the intrinsic data providers: OleDbTransaction in the System.Data. OleDb namespace and SqlTransaction in the System.Data.SqlClient namespace.The SqlTransaction object is implemented using Microsoft SQL Server transactionscreating a SqlTransaction maps directly to the BeginTransaction statement. The OleDbTransaction is implemented within OLE DB. Transactions are created by calling the BeginTransaction method of the Connection object, which returns a reference to a Transaction object. BeginTransaction is overloaded, allowing an IsolationLevel.The Connection must be valid and open when BeginTransaction is called. Connection BeginTransaction Methods BeginTransaction():-Begins a transaction BeginTransaction(IsolationLevel):-Begins a transaction at the specified Isolation Level BeginTransaction (TransactionName)- transaction with the name specified in the Transaction Name string.

BeginTransaction (IsolationLevel, TransactionName):-Begins a transaction at the specified Isolation Level with the name specified in the Transaction Name string Isolation Levels Chaos:-Pending changes from more highly ranked transactions can not be over written ReadCommitted :-Shared

locks are held while the data is being read, but data can be changed before the endof the transaction
ReadUncommitted:-No shared locks are issued and no exclusive locks are honored RepeatableRead:-Exclusive locks are placed on all data used in the query. Serializable:- A rangelock is placed on the DataSet Unspecified:-An existing isolation level cannot be determined

Using Transactions
There are three steps to using transactions after they are created.It is assigned to the commands that will participate in them, then the commands are executed, and finally the transaction is closed by either committing it or rolling it back. Assigning Transactions to a Command Once a transaction has been begun on a connection, all commands executed against that connection must participate in that transaction and if this doesnt happen automaticallyyou must set the Transaction property of the command to reference the transaction. Committing and Rolling Back Transactions The final step in transaction, processing is to commit or roll back the changes that were made by the commands participating in the transaction. If the transaction is committed, all of the changes will be accepted in the data source. If it is rolled back, all of the changes will be discarded, and the data source will be returned to the state it was in before the transaction began. Transactions are committed using the transactions Commit method and rolled back using the transactions Rollback method. Example:-Step To Create Transactions 1. Open the Transactions project from the Visual Studio Start Page or byusing the File menu. 2. Double-click Transactions.cs to display the form in the form designer. 3. Double-click Create. Visual Studio opens the code editor window and adds the Click event handler.

4. Add the following code to the procedure: 5. string s 6. System.Data.OleDb.OleDbTransaction TrnNew; 7. this.cnAccessNwind.Open(); 8. TrnNew = this.cnAccessNwind.BeginTransaction(); 9. s = "Isolation Level: "; 10. s += TrnNew.IsolationLevel.ToString(); 11. MessageBox.Show(s); 12. this.cnAccessNwind.Close(); 13. The code creates a new Transaction using the default method, and then displays its IsolationLevel in a message box. 14. Press F5 to run the application.

Binding Data to Controls


Simple data binding is the ability to bind a control to a single data element. When you need to display and manipulate more than one data element at a time,then this is called complex data binding.Complex data binding is the ability to bind a control to more than one data element and more than one record in a database. Class Hierarchies Relevant to Data Binding

//Text box controlsUsed to display, or accept as input, a single line of text. Can also support multilines. System.Windows.Forms.TextBox class System.Windows.Forms.DataGridTextBox subclass System.Web.UI.WebControls.Textbox class //List controlsEnable you to display a list of items to the user that the user can select by clicking. System.Windows.Forms.ListControl class System.Windows.Forms.ComboBox subclass System.Windows.Forms.ListBox subclass System.Web.UI.WebControls.ListControls class System.Web.UI.WebControls.CheckBoxList subclass System.Web.UI.WebControls.DropDownList subclass System.Web.UI.WebControls.ListBox subclass System.Web.UI.WebControls.RadioButtonList subclass //DataGrid controlsUsed to display data in a

scrollable, tabular grid. System.Windows.Forms.DataGrid class System.Web.UI.WebControls.DataGrid class

Methods Binding For ListBox controls, you can bind the control to a DataSet class using the DataSource and DisplayMember properties as you have seen in our Windows Forms example: ListBox1.DataSource = customer ListBox1.DisplayMember = "Customers.CompanyName" Or, you can use the DataBinding method programmatically to achieve the same results. ListBox1.DataBindings.Add(New System.Windows.Forms.Binding ("SelectedItem", customer, "Customers.CompanyName")) For DataGrid controls, you bind the control to a DataSet class using the DataSource and DataMember properties: DataGrid1.DataMember = "Customers.CustomersOrders" DataGrid1.DataSource = customer Or, use the SetDataBinding method programmatically to achieve the same results: DataGrid1.SetDataBinding(customer,"Customers.CustomersOrders")

ConnectionPooling
A connection pool is a set of database connections .Connection pool are available for an application to use and it is using for enhanced performance. Connection pooling is also usefull for sharing resources. Connection pooling is used to handle the performance of executing commands on a database and it needs a connection to that database to be established before executing a command , .Connection pooling is used with applications that do not have a state. State is a presence between instances. ASP pages are consider stateless because they do not share data between themselves. Stateless applications benefit from connection pooling because they can not hold a connection open by themselves. Connection pooling is also usefull for sharing resources. ConnectionPooling parameter These are four parameters that control most of the connection pooling behavior

Max Pool Size - The maximum size of our connection pool. Default is 100 Min Pool Size - Initial number of connections which will be added to the pool upon its creation. Default is 0. Connect Timeout - Controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds. Pooling - Controls if your connection pooling on or off. Default as you may've guessed is true. Read on to see when we may use Pooling=false setting.

Using ADO within Active Server Pages To use connection pooling with ASP, we can use ADO objects as our database interface and have connection pooling turned on for IIS 3.0. Code For Connection pooling

"initial catalog=emp; Min Pool Size=20;Max Pool Size=500; data source=localhost; Connection Timeout=30; Integrated security=sspi". Using ADO.NET in Windows Forms
1)Formatting Data The Binding object exposes two events, Format and Parse, both support formatting.data for an application. The Format event occurs whenever data is pushed from the data source to the control, and when it is pulled from the control back to the data source.The Format event is used to translate the data from its native format to the format we want to display to the use.The Parse event is used to translate it back to its original format and both events receive a ConvertEventArgs argument ConvertEventArgs Properties 1-The value property 2-The desired property The Value property contains the actual data. When the event is triggered,the value property will contain the original data in its original format. To change the formatting, you set this value to the new data or format within the event handler. The DesiredType property is used when you are changing the data type of the value. Using the Format Event

The Format event occurs both when data is being pushed from the data source and when it is pulled from the control, we must be sure we know which action is taking place before performing any action. If we change the data type of the value, we can use the DesiredType property to perform this check. Using the Parse Event the Parse event occurs when data is being pulled from a control back to the data source, and it is typically used to un-format data that has been customized for display. Because Parse is called only once, this un-formatting operation should always happen.

ADO Versus ADO.NET


ADO ADO .NET

Business Model

Connection-oriented Models used mostly

Disconnected models are used:Message-like Models.

Disconnecte Provided by Record set Provided by Data Adapter and Data set d Access XML Support Limited Robust Support

ADO objects Data Passingcommunicate in binary ADO.NET uses XML for passing the data. mode. Derives information about data implicitly at Leverages known metadata at design time in Design-time run time, based on order to provide better run-time performance and support metadata that is often more consistent run-time behavior. expensive to obtain. Includes implicit behaviors that can not Control of Provides well-defined, factored components with always be required in data access predictable behavior, performance, and an application and that behaviors semantics. can therefore limit performance.

Connection Model

Client application needs to be connected always to data-server while working on the data, unless using client-side Client disconnected as soon as the data is processed. DataSet is disconnected at all times. cursors or a disconnected Record set

ADO Versus ADO.NET Data Types


Code adEmpty adBoolean adTinyInt adSmallInt adInteger adBigInt adUnsignedTinyInt adUnsignedSmallInt adUnsignedInt adUnsignedBigInt adSingle adDouble adCurrency adDecimal adNumeric adDate Symbol null Int16 SByte Int16 Int32 Int64 promoted to Int16 promoted to Int32 promoted to Int64 promoted to Decimal Single Double Decimal Decimal Decimal DateTime

adDBDate adDBTime adDBTimeStamp adFileTime adGUID adError adIUnknown adIDispatch adVariant adPropVariant adBinary adChar adWChar adBSTR adChapter adUserDefined

DateTime DateTime DateTime DateTime Guid ExternalException object object object object byte[] string string string not supported not supported

Simple Data Binding in Windows Forms


1)Create a New Project in VS .NET 1. Create a new project in VS .NET by choosing File, New, and then choosing the Project option. 2. When the New Project dialog box appears, choose Visual C# Projects and Windows Applications. Name this project "simple data binding." This creates a default form for you to start from. Add the Data Connection, Data Adapter, and DataSet

From the Data tab of the Toolbox, drag a OledbDataAdapter object into your form

1. This will automatically invoke the Data Adapter Configuration Wizard. Both the data connection and the data adapter can be fully configured here. a. The wizard creates with the Choose Your Data Connection dialog box. If already exist a connection defined in your project, it will be placed in the dialog box. Otherwise, choose to create a new connection and specify the appropriate connection information b. we will then have to decide to supply SQL statements, build a new stored procedure, or give the name of an existing stored procedure for the data access. In our example we will use the Use SQL Statements option. c. we will be presented with a Generate the SQL Statements dialog box where we will simply type in a valid SQL statement, or you can use the Query Builder option to formulate the SQL query. such as d. SELECT * FROM emp e. The wizard will show we the tasks that it has done and indicate whether the SqlDataAdapter has been configured successfully. 2. After the SqlDataAdapter and DataConnection objects have been configured and added to the form, you must generate a DataSet and then add an instance of this DataSet to the form. We will be binding our TextBox properties to the columns in the DataSet. a. Simply right-click on the oledbDataAdapter that is on your form and choose the Generate Dataset menu option

Generate a new dataset for the form

a. Now,we choose to create a new DataSet using the default name that it provides

(DataSet1). Make sure you have checked the emp table and checked the box for it to be added to the designer. b. When the process finishes, a DataSet instance named DataSet11 will be on the form and a dataset schema will be in the Solutions Explorer (named DataSet1.xsd). Create Text Boxes, Labels, and Buttons Textbox With a name of EmpID and text is blank. Textbox With a name of EmpName and text is blank. Button With a name of ok and text of OK

Bind the Text Boxes to the DataSet

1. From the Forms Designer, select the EmpID text box and go to its property 2. Expand the (DataBindings) node in the properties list and its text property. 3. Within the text property, expand DataSet1 and Emp nodes and select the empid
column from the list 4. Now, from the Forms Designer, select the EmpName text box and press F4. 5. Expand the (DataBindings) node in the properties list and its text property. 6. Within the text property, expand the DataSet1 and Emp nodes and select the empname column from the list.

Now we are ready to complete the application by adding the code to fill the DataSet.

Just double-click on the Ok button to create a method for the Click event. private void button1_Click(object sender, EventArgs e) { oleDbDataAdapter1.SelectCommand.Parameters ["param1"].Value =EmpID.Text.ToString(); empDataSet1.Clear(); oleDbDataAdapter1.Fill(empDataSet1); } } The Forms application, showing simple binding.

Complex Data Binding in Windows Forms


We will build Windows Form that will display all student in a bound ListBox and thestudents's associated marks in a bound DataGrid. A more complex DataSet will be needed that provides the relationship path to traverse from student to marks using the primary key of student (stdid) to foreign key in marks (stdid). we will have to do data bindings for both the ListBox control and the DataGrid control. Create a New Project in VS .NET 1. Create a new project in VS .NET by choosing File, New, and then choosing the Project option.. 2. When the New Project dialog box appears, choose Visual C# Projects and Windows Applications. Name this project "comlexdatabinding". This creates a default form for you to start from. Add the Data Connection and Two Data Adapters we will need to access both the student table and themarks table, so two data adapters will be created, each populating different controls but using one database connection.

From the Data tab of the Toolbox, drag aOledbDataAdapter object into your form. This will automatically invoke the Data Adapter Configuration Wizard. Both the data connection and the data adapter can be fully configured here. a. The wizard starts with the Choose our Data Connection dialog box. If there already exist a connection defined in your project,then it will be placed in the dialog box; otherwise, choose to create a new connection and specify the appropriate connection information . b. Choose the Use SQL Statements option. c. we will be presented with a Generate the SQL Statements dialog box where you will simply type in a valid SQL statement, or you can use the Query Builder option to formulate the SQL query.such as: SELECT stdid,stdname FROM student

d. Finally, the wizard will show you the tasks that it has done and indicate whether the
oledbDataAdapter has been configured successfully. we need one more data adapter for access to the mrks table. Drag another oledbDataAdapter object onto the form. a. Again, the wizard starts with the Choose Your Data Connection dialog box. b. Choose the Use SQL Statements option. c. we will be presented with a Generate the SQL Statements dialog box where you will type the following query: d. SELECT subid, stdid, subname,mark FROM marks d .Then the wizard will show we the tasks that it has done and indicate whether the oledbDataAdapter has been configured successfully . Generate a DataSet Now that the OledbDataAdapter and DataConnection objects have been configured and added to the form, you must generate a DataSet and then add an instance of this DataSet to the form. 1. From the Data menu in Visual Studio, simply choose the Generate Dataset option. 2.

1.

XML Schema editorSTUDENTDS.xsd schema file.

Next, drag a Relation object onto the Orders table

Adding the ListBox and DataGrid Controls create the ListBox to display all of the Sudent Names from the Student table.

a. Drag a ListBox object from the Windows Forms tab of the Toolbox onto the
Form.

b. Press F4 to go right to the properties of this ListBox. c. For the DataSource property, you will need to select the dtatsaet1 data
source.

d. For the DisplayMember property, you will select student , expand this node,
and select studentname.shows the complete ListBox property. the DataGrid control to display all of the Orders that are associated with a particular Company that is selected.

e. Drag a DataGrid object from the Windows Forms tab of the toolbox onto the
Form.

f. Press F4 to go right to the properties of this DataGrid. g. For the DataSource property, you will need to select the student data source.

h. And, for the DisplayMember property, you will select and expand student, and
then select marks Just double-click on the form to create a handler for the form's Load event. You will need to clear the DataSet first, and then fill each data adapter that we defined. datsaet1.Clear() OledbDataAdapter1.Fill(dataset1) OledbDataAdapter2.Fill(dataset1)

Displaying Hierarchical Data Using the DataGrid


1.In the Solution Explorer, double-click DataGridview.cs Visual Studio opens the form in the form designer. 2. Select the DataGridview1. 3. In the Properties window, select the Choose DataSource property, expand the drop-down list, and then select add new project

click the button next and add connection and then click next and choose table marks and then click finish

p="" border="0" height="451" width="576"> 4. Now go to edit colomns and change Header Text name as required

<=""

5. now the form is

6.now run the program

Display Data Using the DataGridview and oledbconnection


Create a New Project in VS .NET 1. Create a new project in VS .NET by choosing File, New, and then choosing the Project option.. 2. When the New Project dialog box appears, choose Visual C# Projects and Windows Applications. Name this project "oledbconnection1". This creates a default form for you to start from. ADD DATA SOURCE Go to server Explorer and right click on data Connections and clik then Add Connectin

< choose oledb data source for database name click the browse and give the path of database student.mdb

then click the test connection. if text connection is succeeded click the ok button otherwise again try to connect to database. Adding the Button and DataGrid Controls

using using using using using using using

System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace using_oledbconn { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void showmark_Click(object sender, EventArgs e) { OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=F:\\student.mdb"); con.Open(); OleDbDataAdapter ad = new OleDbDataAdapter("select * from marks", con); DataSet ds=new DataSet(); ad.Fill(ds,"marks"); ds.GetXml(); dataGridView1.DataSource=ds.Tables[0]; } } }

DataView Object
The DataView object is more than a replacement for the DataTables Select method . Not only

are the results of the Select method on a DataTable not directly data bindable, but it is also not a very efficient method to query rows. Creating a DataView A DataView can be created using any of the three constructor overloads it supports. The first constructor overload allows you to create a DataView but not specify any information DataView dv = new DataView() ; The second constructor directly ties the DataView to a DataTable DataView dv = new DataView(TableName) ; The third and final constructor of DataViews allows you to specify all that information in one line of code. DataView dv =new DataView( EmpTable, "EmpID = 1001", "EmpName", DataViewRowState.Unchanged); Example of DataView Object

private void DataViewexample() { // Create one DataTable with one column. DataTable tb = new DataTable("student"); DataColumn dc = new DataColumn("stuentname", Type.GetType("System.String")); table.Columns.Add(colItem); // Add five items. DataRow NewRow; for(int i = 0; i <5; i++) { NewRow = table.NewRow(); NewRow["studentname"] = "studentname " + i; table.Rows.Add(NewRow); } // Change the values in the table. table.Rows[0]["studentname"]="Ashish"; table.Rows[1]["studentname"] = "Aditya"; tb.AcceptChanges();

// Create two DataView objects with the same table. DataView firstView = new DataView(table); DataView secondView = new DataView(table); // Print current table values. PrintTableOrView(table,"Current Values in Table"); // Set first DataView to show only modified // versions of original rows. firstView.RowStateFilter=DataViewRowState.ModifiedOriginal ; // Print values. PrinSTDtTableOrView(firstView,"First DataView: ModifiedOriginal"); // Add one New row to the second view. DataRowView rowView; rowView=secondView.AddNew(); rowView["studentname"] = "Anil"; // Set second DataView to show modified versions of // current rows, or New rows. secondView.RowStateFilter=DataViewRowState.ModifiedCurr ent | DataViewRowState.Added; // Print modified and Added rows. PrintTableOrView(secondView, "Second DataView: ModifiedCurrent | Added"); } private void PrintSTDTableOrView(DataTable table, string s) { // This function prints values in the table or DataView. Console.WriteLine("\n" + s); for(int i = 0; i<table.Rows.Count;i++) { Console.WriteLine("\table" + table.Rows[i] ["studentname"]); } Console.WriteLine(); } private void PrintSTDTableOrView(DataView view, string label) { // This overload prints values in the table or DataView. Console.WriteLine("\n" + s); for(int i = 0; i<view.Count;i++) { Console.WriteLine("\table" + view[i][""studentname"]); }

Console.WriteLine();

Displaying the Row States in C#

private static void DisplayROWs(string , DataTable table) { Console.Clear(); Console.WriteLine("\n"); Console.WriteLine(s); Console.WriteLine("------------------------------------------"); foreach (DataRow dr in table.Rows) { Console.WriteLine(dr.RowState.ToString()); } Console.WriteLine("\nPress Enter to Continue ..") ; Console.Read() ; }

Filling a DataTable and Displaying the Row States in C#


static void Main(string[] args) { using (SqlConnection scon = new SqlConnection(connectionString)) { SqlCommand scmd = scon.CreateCommand(); scmd.CommandText = "Select * from student"; SqlDataAdapter sqlDa = new SqlDataAdapter(scmd); DataTable StudentTable = new DataTable("student"); sqlDa.Fill(StudentTable); DisplayRowStates( "Row states for a freshly filled DataTable:",StudentTable); } }

Making Changes to the DataTable in C#


DataRow dr; // Make Changes - Modify the puppy dr = StudentTable.Rows[0]; dr["StudentName"] = "Anil"; // Make Changes - Delete the cat dr = StudentTable.Rows[1]; dr.Delete(); // Leave the Horse untouched. // Make Changes - Insert a Record dr = StudentTable.NewRow(); dr["StudentID"] = 4; dr["StudentName"] = "Ajay"; StudentTable.Rows.Add(dr); DisplayRowStates("Row states for a modified DataTable:", StudentTable);

Setting Various Commands in C#


// Update the changes back to the database. SqlCommandBuilder sqlcommr = new SqlCommandBuilder(sqlDa); // Setup Update Command sqlDa.UpdateCommand = sqlcommr.GetUpdateCommand(); Console.WriteLine("Update Command: " + sqlDa.UpdateCommand.CommandText); // Setup Insert Command sqlDa.InsertCommand = sqlcommr.GetInsertCommand(); Console.WriteLine("Insert Command: " + sqlDa.InsertCommand.CommandText); // Setup Delete Command sqlDa.DeleteCommand = sqlcommr.GetDeleteCommand() ; Console.WriteLine("Delete Command: " + sqlDa.DeleteCommand.CommandText); sqlDa.Update(animalsTable);

Moving Large Amounts of Data Using SqlBulkCopy


BCP (Bulk Copy) and DTS (Data Transformation Services) both work much faster than a row by row SQL statement insert would be. In .NET Framework if we want to implement the functionality of copying over vast amounts of data between databases then the DataSet or data adapter would have been a very poor option because filling the DataSet, sending it across, changing all row states, iterating over each single row, and executing one SQL command per row would take so long time . .NET 2.0, has introduced a new class specifically for this purpose: the SqlBulkCopy class. , SqlBulkCopy copies data from one table to another over two different open SqlConnections. The two different open SqlConnections can also point to the same database if that is what you prefer, or they may point to different databases. There is following step using BCP:1. Start a new Console application, and name it SqlBulkCopy. 2. The aim of this application is to fast copying of data between two tables of identical structure. So first step is to create two tables of identical structure. You can easily achieve this with the following SQL statement: Create Table student as Select * from student where 1 = 2 3. we will need two different SqlConnections: one for the data reader that the SqlBulkCopy will read from, and one for SqlBulkCopy itself. So lets start by creating the data reader that will read from the Student table. This can be seen in the following code:

using (SqlConnection sqlconn = new SqlConnection(connectionString)) { SqlCommand sqlcomm = sqlconn.CreateCommand(); sqlcomm.CommandText = "Select * from student"; sqlconn.Open(); SqlDataReader dr = sqlcomm.ExecuteReader();

} // Dispose is called on firstConnection 4.The second part of the application uses the SqlBulkCopy object instance to insert data read from the created data reader into the StudentCopy table.

using (SqlConnection sqlconn = new SqlConnection(connectionString)) { SqlCommand sqlcomm = sqlconn.CreateCommand(); sqlcomm.CommandText = "Select * from Student"; sqlconn.Open(); SqlDataReader dr = sqlcomm.ExecuteReader(); using (SqlConnection secondConnection = new SqlConnection(connectionString)) { SqlBulkCopy bc = new SqlBulkCopy(secondConnection); bc.DestinationTableName = "StudentCopy"; bc.WriteToServer(dr); bc.Close(); dr.Close(); } // Dispose is called on sqlconn }

5. Thats it. Compile and run the application to copy rows from one table to another in a screamingly fast manner. Connect to a larger table and write up an equivalent application leveraging DataSets and data adapters, and notice the time it takes in comparison with SqlBulkCopy. You can see that SqlBulkCopy is hundreds to thousands of times faster.

Editing Disconnected Data


The various objects in ADO.NET that compose the disconnected part of ADO.NET , have ability to make edits or modifications to themselves.

there are mainly three kinds of modification operations that can be perform on disconnected data: Add new rows Modify existing rows Delete existing rows

Add New Rows There are two ways to add a new row to a DataTable, and two ways to add existing rows (from other DataTables or Detached rows) to a DataTable. 1)The first way assumes thate we have a schema or at least a structure preloaded to the DataTable. example:rowInQuestion = StudentTable.NewRow(); rowInQuestion["StudentID"] = 4; rowInQuestion["SudentName"] = "Ashish"; studentTable.Rows.Add(rowInQuestion); 2)The second method to add a new DataRow into a DataTable is to use the LoadDataRow method. Load data row method allows you to add a new DataRow and set its various values in one convenient method call. Example:object[] rowVals = {"4", "Ashish"} ; StudentTable.LoadDataRow(rowVals, false); Modify Existing Rows Two methods exist for adding existing DataRows to a DataTable. The first is the ImportRow method, which simply takes a DataRow as a parameter, and the second is the Merge method, which merges two sets of disconnected data (DataSet, DataTable, DataRow array, etc.) and The DataRowState at the end of this edit would be Modified Example:-

rowInQuestion = StudentTable.Rows[0]; rowInQuestion["StudentName"] = "Anil"; 2)There second way of modifying rows, The DataRow object has a method called BeginEdit, and a matching method called EndEdit.we can modify the rows between these two method calls and difference is that all the changes are buffered until you call EndEdit. If, in case you change your mind, you call CancelEdit instead, all the changes are rolled back. Example:-rowInQuestion = StudentTable.Rows[0]; rowInQuestion.BeginEdit(); rowInQuestion["StudentName"] = "Aditya"; rowInQuestion.EndEdit() ; rowInQuestion = StudentTable.Rows[0]; rowInQuestion.ItemArray = new object[] {null, "kamal"} ; Delete Existing Rows using delete method we can delete the row rowInQuestion = StudentTable.Rows[1]; rowInQuestion.Delete() Another way of removing a row is by using either the Remove or RemoveAt method on the DataRowCollection object (DataTable.Rows is of DataRowCollection type) StudentTable.Remove(rowInQuestion) ; // or StudentTable.RemoveAt(1) ; The DataRowVersion Enumeration Constant Current Description This constant will give you the current value stored inside a column.

Original

This constant allows you to fetch the original value stored inside a column.

Proposed

Default

This constant allows you to fetch the proposed value after a BeginEdit and update but before an EndEdit. This constant retrieves the value as if the constant wasnt specified

Copy a DataTable
we can do copy of datatable with the help of copy();

private void button1_Click(object sender, EventArgs e) { OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\\student.mdb"); con.Open(); OleDbCommand cmd =new OleDbCommand("select * from marks", con); DataTable tb = new DataTable(); tb.Load(cmd.ExecuteReader(CommandBehavior.CloseConn ection)); DataTable copytable = tb.Copy(); tb = null; dataGridView1.DataSource = copytable; }

DataTable Events
DataTable exposes a set of events and the events can be captured and handled in order to update the user interface, or to validate edits or deletes before they are committed. Not including the event inherited from MarshalByValueComponent.Disposed, there are nine events in all, and they all work in more-or-less the same way, with similar arguments. System.Data.DataTable Events Event ColumnChanging Description Occurs when a value is being changed in the specified DataColumn in DataRow.

ColumnChanged

RowChanging

RowChanged TableClearing TableCleared RowDeleting TableNew Row RowDeleted

Occurs after a value has been changed in the specified DataColumn in a DataRow. Occurs when a DataRow is changing. This event will fire each time a change is made to the DataRow, after the ColumnChanging event has fired. Occurs after a DataRow has been changed successfully. Occurs when the table is being cleared. Occurs after the table has been cleared. Occurs when a DataRow is about to be deleted. Occurs right after a new row has been generated. Occurs after a DataRow is successfully deleted from the DataTable.

Each of the DataTable events works in the same fashion. Handlers for the column-related events (ColumnChanging and ColumnChanged) receive a DataColumnChangeEventArgs object, which exposes three properties. DataColumnChangeEventArgs Properties Property Description Get DataColumn object with the changing value. Gets or sets the proposed value that is, the new value being assigned to the column. In a ColumnChanging event handler

Column

Proposed Value

Row

Gets the DataRow object with the changing value

The handlers for the row-related events other than the TableNewRow (i.e., RowChanging, RowChanged, RowDeleting, and RowDeleted) take a DataRowChangeEventArgs object, which exposes just two properties DataRowChangeEventArgs Properties Property Action Description Gets the action (added, changed, deleted, etc.) that will occur/has occurred on the DataRow. Gets the DataRow object upon which the action will occur/has occurred.

Row

Usage of DataTable Events


DataTable events can be split into three main categories: Column-based: ColumnChanging, ColumnChanged Row-based: RowChanging, RowChanged, RowDeleting, RowDeleted Table-based: TableClearing, TableCleared, TableNewRow Setting Up Various Event Handlers on a DataTable in C#

CompanyTAble.ColumnChanged += new DataColumnChangeEventHandler(CompanyTAble_ColumnChanged); CompanyTAble.ColumnChanging += new DataColumnChangeEventHandler(CompanyTAble_ColumnChanging); CompanyTAble.RowChanged += new DataRowChangeEventHandler(CompanyTAble_RowChanged); CompanyTAble.RowChanging += new DataRowChangeEventHandler(CompanyTAble_RowChanging); CompanyTAble.RowDeleted += new DataRowChangeEventHandler(CompanyTAble_RowDeleted); CompanyTAble.RowDeleting += new DataRowChangeEventHandler(CompanyTAble_RowDeleting);

Implementations for the Event Handlers in C#

private static void CompanyTable_ColumnChanged (object sender, DataColumnChangeEventArgs e) { Console.WriteLine("CompanyTable_ColumnChanged"); Console.WriteLine(" Value: " + e.Row["Name"].ToString()); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); } private static void CompanyTable_ColumnChanging (object sender, DataColumnChangeEventArgs e) { Console.WriteLine("CompanyTable_ColumnChanging"); Console.WriteLine(" Value: " + e.Row["Name"].ToString()); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); } private static void CompanyTable_RowChanged

(object sender, DataRowChangeEventArgs e) { Console.WriteLine("CompanyTable_RowChanged"); Console.WriteLine(" Value: " + e.Row["Name"].ToString()); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); } private static void CompanyTable_RowChanging (object sender, DataRowChangeEventArgs e) { Console.WriteLine("CompanyTable_RowChanging"); Console.WriteLine(" Value: " + e.Row["Name"].ToString()); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); } private static void CompanyTable_RowDeleted (object sender, DataRowChangeEventArgs e) { Console.WriteLine("CompanyTable_RowDeleted"); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); } private static void CompanyTable_RowDeleting (object sender, DataRowChangeEventArgs e) { Console.WriteLine("CompanyTable_RowDeleting"); Console.WriteLine(" RowState: " + e.Row.RowState.ToString()); }

Merge Table
Merge Case 1: Different Table Structures,No Primary Key In the strongly typed DataSet, Table0 can be used as a sample table that has no primary keys defined on it.

2)Binding the student datasource in table1 and table2

<="" p="" border="0" height="494" width="491"> 3)write the code

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace WindowsFormsApplication13 { public partial class Form1 : Form { public Form1() {

InitializeComponent();

private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'studentDataSet.student' table. You can move, or remove it, as needed. this.studentTableAdapter.Fill(this.studentDataSet.s tudent); // TODO: This line of code loads data into the 'studentDataSet.std1' table. You can move, or remove it, as needed. this.std1TableAdapter.Fill(this.studentDataSet.std1 ); } e) private void button1_Click(object sender, EventArgs {

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=F:\\student.mdb"); OleDbDataAdapter ad = new OleDbDataAdapter("select * from std1", con); DataTable tb1 = new DataTable(); ad.Fill(tb1); dataGridView4.Visible = true; dataGridView4.DataSource = tb1; OleDbDataAdapter ad1 = new OleDbDataAdapter("select * from student", con); DataTable tb2 = new DataTable(); ad1.Fill(tb2); tb1.Merge(tb2); dataGridView3.DataSource = tb1; dataGridView3.Visible = true; dataGridView1.Visible = false; label1.Visible = false; label2.Visible = false; } } }

4)Run thr program

5)click the merge button Data after Merge

Same Table Structures, with Primary Key


In the strongly typed DataSet, Table1 can be used as a sample table that has primary keys defined on it.

2) create the column with primary key DataTable ftb = new DataTable(); DataTable stb = new DataTable(); ftb.Columns.Add("Eno", typeof(Int32)); ftb.Columns.Add("Ename", typeof(String));

ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Eno"] }; stb.Columns.Add("Eno", typeof(Int32)); stb.Columns.Add("Ename", typeof(String));

3)write the code using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable ftb = new

DataTable(); DataTable stb = new DataTable(); private void Form1_Load(object sender, EventArgs e) { ftb.Columns.Add("Eno", typeof(Int32)); ftb.Columns.Add("Ename", typeof(String)); ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Eno"] };

ftb.LoadDataRow(new object[] { "1", "Ashish" }, true); ftb.LoadDataRow(new object[] { "2", "KAMAL" }, true); stb.Columns.Add("Eno", typeof(Int32)); stb.Columns.Add("Ename", typeof(String)); stb.LoadDataRow(new object[] { "2", "Aditya" }, true); stb.LoadDataRow(new object[] { "3", "Anil" }, true); dataGridView1.DataSource = ftb; dataGridView2.DataSource = stb; } private void button1_Click(object sender, EventArgs e) { ftb.Merge(stb); dataGridView1.DataSource =ftb; dataGridView2.Visible = false;

} } }

label1.Text = "After Merging"; label2.Visible = false;

Merge Case 2: Same Table Structures,No Primary Key


In the strongly typed DataSet, Table0 can be used as a sample table that has no primary keys defined on it.

2)Binding the student datasource in table1 and table2

3)write the code

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace WindowsFormsApplication14 { public partial class Form1 : Form { public Form1() {

InitializeComponent();

private void Form1_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'studentDataSet.student2' table. You can move, or remove it, as needed. this.student2TableAdapter.Fill(this.studentDataSet.st udent2); // TODO: This line of code loads data into the 'studentDataSet.std1' table. You can move, or remove it, as needed. this.std1TableAdapter.Fill(this.studentDataSet.std1); } private void button1_Click(object sender, EventArgs e) { OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB. 4.0;Data Source=F:\\student.mdb"); OleDbDataAdapter ad = new OleDbDataAdapter("select * from std1", con); DataTable tb1 = new DataTable(); ad.Fill(tb1); //dataGridView4.Visible = true; //dataGridView4.DataSource = tb1; OleDbDataAdapter ad1 = new OleDbDataAdapter("select * from student2", con); DataTable tb2 = new DataTable(); ad1.Fill(tb2); tb2.Merge(tb1); dataGridView3.DataSource = tb2; dataGridView3.Visible = true; dataGridView1.Visible = false; dataGridView2.Visible = false; label1.Visible = false; label2.Visible = false; } } }

4)Run thr program

5)click the merge button Data after Merge

Merge Case 4: Common Column, with Primary Key


In the strongly typed DataSet, Table1 can be used as a sample table that has primary keys defined on it.

2) create the column with primary key DataTable ftb = new DataTable(); DataTable stb = new DataTable(); ftb.Columns.Add("Sno", typeof(Int32)); ftb.Columns.Add("Sname", typeof(String));

ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Sno"] }; stb.Columns.Add("Sno", typeof(Int32)); stb.Columns.Add("Smark", typeof(String));

3)write the code

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1()

InitializeComponent(); } DataTable ftb = new DataTable(); DataTable stb = new DataTable(); private void Form1_Load(object sender, EventArgs e) { ftb.Columns.Add("Sno", typeof(Int32)); ftb.Columns.Add("Sname", typeof(String)); ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Sno"] };

ftb.LoadDataRow(new object[] { "1", "Ashish" }, true); ftb.LoadDataRow(new object[] { "2", "KAMAL" }, true); stb.Columns.Add("Sno", typeof(Int32)); stb.Columns.Add("Smark", typeof(Int32)); stb.LoadDataRow(new object[] { "1", "480" }, true); stb.LoadDataRow(new object[] { "2", "495" }, true); dataGridView1.DataSource = ftb; dataGridView2.DataSource = stb; } private void button1_Click(object sender, EventArgs e) { ftb.Merge(stb);

=ftb; false;

dataGridView1.DataSource dataGridView2.Visible = label1.Text = "After Merging"; label2.Visible = false;

} } }

4)Run the program

5)click the merge button

Merge Case 5: Absolutely Different Table Structures


In this case, the two table structures have nothing in common. All the columns differ

2) create the different column DataTable ftb = new DataTable(); DataTable stb = new DataTable(); ftb.Columns.Add("Sno", typeof(Int32)); ftb.Columns.Add("Sname", typeof(String)); ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Sno"] }; stb.Columns.Add("Smark", typeof(Int32)); stb.Columns.Add("Sgrade", typeof(String));

3)write the code

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.OleDb;

namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1()

InitializeComponent(); } DataTable ftb = new DataTable(); DataTable stb = new DataTable(); private void Form1_Load(object sender, EventArgs e) { ftb.Columns.Add("Sno", typeof(Int32)); ftb.Columns.Add("Sname", typeof(String)); // ftb.PrimaryKey = new DataColumn[] { ftb.Columns["Sno"] };

ftb.LoadDataRow(new object[] { "1", "Ashish" }, true); ftb.LoadDataRow(new object[] { "2", "KAMAL" }, true); ftb.LoadDataRow(new object[] { "3", "Mohit" }, true); ftb.LoadDataRow(new object[] { "4", "Aditya" }, true); stb.Columns.Add("Smark", typeof(Int32)); stb.Columns.Add("Sgrade", typeof(string)); stb.LoadDataRow(new object[] { "480", "I" }, true); stb.LoadDataRow(new object[] { "255", "II" }, true); stb.LoadDataRow(new object[] { "295", "II" }, true); stb.LoadDataRow(new object[] { "380", "I" }, true); dataGridView1.DataSource = ftb; dataGridView2.DataSource =

stb; } private void button1_Click(object sender, EventArgs e) { ftb.Merge(stb); dataGridView3.DataSource =ftb; dataGridView1.Visible = false; dataGridView2.Visible = false; dataGridView3.Visible =true; label1.Text = "After Merging"; label2.Visible = false; } } }

4)Run the program

Adding Records Using Mapped Names


TableMappings and ColumnMappings help you bridge this translation gap of different column/table names in fetching data. The same concepts can be applied to other database operations, such as inserting a new record or updating an existing Examople: Example of Adding a Record Using C#

using using using using using using

System; System.Collections.Generic; System.Text; System.Data.OleDb; System.Data.Common; System.Data;

namespace addrecord

{ class Program { static void Main(string[] args) { DataSet ds = new DataSet("Users"); try { // Define a connection object OleDbConnection dbConn = new OleDbConnection( "Provider=Microsoft.Jet.OLEDB.4.0;" + "Password=;User ID=Admin;Data Source=db.mdb"); // Create a data adapter to retrieve records from DB OleDbDataAdapter dataadp = new OleDbDataAdapter("SELECT ID,Ename,En0,cty,st" + " FROM Emp", dbConn); // Define each column to map DataColumnMapping dcmUserID = new DataColumnMapping("ID", "UserID"); DataColumnMapping dcmEmpName = new DataColumnMapping("Ename", "Name"); DataColumnMapping dcmEmpNumber = new DataColumnMapping("En0", "Eno"); DataColumnMapping dcmCity = new DataColumnMapping("cty", "City"); DataColumnMapping dcmState = new DataColumnMapping("st", "State"); // Define the table containing the mapped columns DataTableMapping dtmUsers = new DataTableMapping("Table", "User"); dtmUsers.ColumnMappings.Add(dcmUserID); dtmUsers.ColumnMappings.Add(dcmEmpName); dtmUsers.ColumnMappings.Add(dcmEmpNumber); dtmUsers.ColumnMappings.Add(dcmCity); dtmUsers.ColumnMappings.Add(dcmState); // Activate the mapping mechanism dataadp.TableMappings.Add(dtmUsers); // Fill the dataset dataadp.Fill(ds); // Declare a command builder to create SQL instructions // to create and update records. OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadp); // Insert a new record in the DataSet DataRow r = ds.Tables["User"].NewRow(); r["Eno"] = "1050"; r["City"] = "Delhi";

r["State"] = "NewDelhi"; ds.Tables["User"].Rows.Add(r); // Insert the record in the database dataadp.Update(ds.GetChanges()); // Align in-memory data with the data source ones ds.AcceptChanges(); // Print successfully message Console.WriteLine("A new record has been" + " added to the database."); } catch (Exception ex) { // Reject DataSet changes ds.RejectChanges(); // An error occurred. Show the error message Console.WriteLine(ex.Message); } } } }

Updating Records Using Mapped Names


TableMappings and ColumnMappings help you bridge this translation gap of different column/table names in fetching data. The same concepts can be applied to other database operations, such as inserting a new record or updating an existing Example: Example of Adding a Record Using C# using using using using using using System; System.Collections.Generic; System.Text; System.Data.OleDb; System.Data.Common; System.Data;

namespace udatingrecord { class Program { static void Main(string[] args) { DataSet ds = new DataSet("Users"); try { OleDbConnection dbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;"

+ "Password=;User ID=Admin;Data Source=db.mdb"); // Create a data adapter to retrieve records from db OleDbDataAdapter dataadapt = new OleDbDataAdapter("SELECT ID,fn,ln,cty,st" + " FROM tabUsers", dbConn); // Define each column to map DataColumnMapping DmUserID = new DataColumnMapping("ID", "UserID"); DataColumnMapping DmFirstName = new DataColumnMapping("fn", "FirstName"); DataColumnMapping DmLastName = new DataColumnMapping("ln", "LastName"); DataColumnMapping DmCity = new DataColumnMapping("cty", "City"); DataColumnMapping DmState = new DataColumnMapping("st", "State"); // Define the table containing the mapped columns new DataTableMapping("Table", "User"); dtmUsers.ColumnMappings.Add(DmUserID); dtmUsers.ColumnMappings.Add(DmFirstName); dtmUsers.ColumnMappings.Add(DmLastName); dtmUsers.ColumnMappings.Add(DmCity); dtmUsers.ColumnMappings.Add(DmState); // Activate the mapping mechanism daUsers.TableMappings.Add(dtmUsers); // Fill the dataset daUsers.Fill(ds); DataColumn[] dckey = { ds.Tables["User"].Columns["UserID"] }; ds.Tables["User"].PrimaryKey = dckey; // Declare a command builder to create SQL instructions // to create and update records. OleDbCommandBuilder cb = new OleDbCommandBuilder(daUsers); // Update an existing record in the DataSet DataRow r = ds.Tables["User"].Rows.Find(8); if (r != null) { r["FirstName"] = "Ashish"; r["LastName"] = "Gupta"; r["City"] = "URAI"; r["State"] = "UP"; // Update the record in the database daUsers.Update(ds.GetChanges()); // Align in-memory data with the data source ones ds.AcceptChanges(); // Print success message Console.WriteLine("The record has been updated " + "successfully.");

} else { Console.WriteLine("No record found..."); } } catch (System.Exception ex) { ds.RejectChanges(); // An error occurred. Show the error message Console.WriteLine(ex.Message); } } } }

Working with Stored Procedures


"a precompiled collection of SQL statements and optional control-of-flow statements stored under a name and processed as a unit". Stored procedures allow a more flexibility offering capabilities such as conditional logic .Bandwidth and execution time are reduced because stored procedures are stored within the DBMS,. because a single stored procedure can execute a complex set of SQL statements. SQL Server pre-compiles stored procedures such that they execute optimally and client developers are abstracted from complex designs. They would simply need to know the stored procedure's name and the type of data it returns. To add a new stored procedure to the Northwind Microsoft SQL database, perform these steps. 1. Load SQL Server Enterprise Manager, found in the Microsoft SQL Server program group. 2. Expand the tree "Microsoft SQL Servers," "SQL Server Group," and locate your database server. With SQL installed locally, the default server will be (LOCAL 3. Locate and expand the Student database. Select Stored Procedures. On the right side of the screen, you'll see any default stored procedures included with the student database. 4. Right-click anywhere on the right pane of the Enterprise Manager and select New Stored Procedure.

Simple insert Stored Procedure use student create procedure studentinsertproc @stdid text,@subid text,@subname text,@mark int as insert into student (stdid

,subid,subname,mark)values(@stdid,@subid,@subname,@mark) studentinsertproc '10001','101','computer graphics',85 studentinsertproc '10002','101','computer graphics',65, studentinsertproc '10003','101','computer graphics',75 studentinsertproc '10004','101','computer graphics',55 studentinsertproc '10005','101','computer graphics',85 studentinsertproc '10006','101','computer graphics',87 select * from student

5)select and press F5

Stored Procedures Comparison with functions


1)In Stored procedures , RETURN keyword is used but without any value being passed. 2)Functions return a value (using the RETURN keyword), but for stored procedures this is not compulsory. 3)A function is a subprogram written to perform certain computations and return a single value. 4)Functions could be used in SELECT statements, provided they dont do any data manipulation. procedures cannot be included in SELECT statements. 5)A function can have only IN parameters, while stored procedures may have OUT or INOUT parameters. 6)A stored procedure can return multiple values using the OUT parameter or return no value at all. Stored Procedures Comparison with view 1)View can be used as a table object A procedure cannot be used as a table object. 2)you cannot accept parameters and do looping inside a view. you can accept parameters and do looping inside a procedure

Advantage of Stored Procedures Advantage There are following advantage of stored procedure: Execution plan retention and reuse Query auto-parameterization Encapsulation of business rules and policies Application modularization Sharing of application logic between applications Access to database objects that is both secure and uniform Consistent, safe data modification Network bandwidth conservation Support for automatic execution at system start-up Enhanced hardware and software capabilities Improved security Reduced development cost and increased reliability Centralized security, administration, and maintenance for common routines

Disadvantage If you want to switch to using another vendor's database, then you have to rewrite your stored procedures. Stored procedures are easy to misuse. If you place business logic in them, then you are not separating business logic from data logic - a maintenance headache. There are emerging alternatives to them that remove some of the disadvantages - such as LINQ in the Microsoft .NET world

Stored Procedures Example


1)Show data using stored procedure code for select procedure create procedure studentselectalproc1 as select * from student using using using using using using using using using System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.SqlClient;

namespace WindowsFormsApplication19 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=R4R03\\SQLEXPRESS;Initial Catalog=ashish ;Integrated Security=True"); con.Open(); SqlCommand cmd=new SqlCommand("studentselectalproc1",con); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); cmd.CommandType = CommandType.StoredProcedure; dataGridView1.DataSource = ds.Tables[0];

} }

2)Insert data using stored procedure code for Insert procedure create procedure studentinsertproc @stdid text, @subid text, @subname text, @mark int as insert into student subid, subname ,mark) values ( @stdid, @subid, @subname, @mark )

(stdid, using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq;

using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication19 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=R4R03\\SQLEXPRESS;Initial Catalog=student ;Integrated Security=True"); con.Open(); SqlCommand cmd=new SqlCommand("studentinsertproc",con); SqlParameter spm = new SqlParameter(); cmd.Parameters.AddWithValue("@stdid", textBox1.Text); cmd.Parameters.AddWithValue("@subid", textBox2.Text); cmd.Parameters.AddWithValue("@subname", textBox3.Text); cmd.Parameters.AddWithValue("@mark", Convert.ToInt32( textBox4.Text)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); }

} }

3)Update data using stored procedure code for Update procedure create proc updatestdrecordproc @stdid nchar(10),@stdname nchar(10), @mark int as update student set stdname=@stdname,mark=@mark where stdid=@stdid

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.SqlClient;

namespace WindowsFormsApplication19 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=R4R03\\SQLEXPRESS;Initial Catalog=studentrecord;Integrated Security=True"); con.Open(); SqlCommand cmd=new SqlCommand("updatestdrecordproc",con); SqlParameter spm = new SqlParameter(); cmd.Parameters.AddWithValue("@stdid", textBox1.Text); cmd.Parameters.AddWithValue("@stdname", textBox2.Text); cmd.Parameters.AddWithValue("@mark", Convert.ToInt32( textBox3.Text)); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); }

} }

3)Delete data using stored procedure

code for Update procedure create proc delstdrecordproc @stdid nchar(10) as delete from student where stdid=@stdid

using using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms; System.Data.SqlClient;

namespace WindowsFormsApplication19 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=R4R03\\SQLEXPRESS;Initial Catalog=studentrecord;Integrated Security=True"); con.Open(); SqlCommand cmd=new SqlCommand("delstdrecordproc",con); SqlParameter spm = new SqlParameter(); cmd.Parameters.AddWithValue("@stdid", textBox1.Text);

cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); }

} }

Using ADO.NET in Web Forms


1)GRIDIEW Add a DataGrid to a Web Form 1. Open the UsingWebForms project from the Start page or the File menu. 2. In the Solution Explorer, double-click the DataGrid.aspx file. Microsoft Visual Studio .NET opens the page in the form designer.

3. Select the DataGrid, and then click left corner the bottom pane of the Properties window. and choose new data source

4)select new data source and press OK

5)Select New connection

6)change data source

7)Select datasource

8)Fill server Name name select are enter database name and press ok button

9)Save the connection and press OK button

10)Select columns from a table and press next button

11)Click Test query for preview data and press finish button

12)select datasource name

13)press F5 and run the program

Using the DataList Control


Add a DataListto a Web Form 1. Open the UsingWebForms project from the Start page or the File menu. 2. In the Solution Explorer, double-click the DataList.aspx file. Microsoft Visual Studio .NET opens the page in the form designer. 3. Drag a DataList control from the Web Form tab of the Toolbox onto the

form designer. Visual Studio adds a placeholder for the DataList control.

4)Select the DataGrid, and then click left corner the bottom and select on choose data source

Select a Data source Type and then press OK button

5)Select New connection

6)change data source

7)Select datasource

8)Fill server Name name select r enter database name and press ok button

9)Save the connection and press OK button

10)Select columns from a table and press next button

11)Click Test query for preview data and press finish button

12)select datasource name

13)press f5 and run the program

COM Interoperability
Using the COM Interop functions provided by the .NET Framework, you can gain access to all the objects, methods, and events that are exposed by any COM object simply by establishing a reference to it. This includes previous versions of ADO and COM objects that youve developed using them. The .NET Framework creates an interop assembly that handles communication between The .NET Framework and COM. The interop assembly handles a number of tasks, but the most important is data type marshaling.

COM Data Type Marshaling Com Data Type bool Int32 Short unsigned char, byte wchar_t, unsigned short unsigned long, unsigned int unsigned hyper float double VARIANT BOOL void * HRESULT CURRENCY SCODE LPSTR LPWSTR VARIANT DECIMAL IDispatch DATE BSTR IUnknown* SAFEARRAY(type) long, decimal Int32 String Object Object Decimal object Date Tiime String Object type[] int Int32 .NET Framework Type char, small SByte Int16l Byte UInt16 UINT32 UInt64 single Double Boolean IntPtr Int16 or IntPtr

Using ADOX in the .NET Framework


ADOX, more formally the Microsoft ADO Extensions for DDL and Security, exposes an object model that allows data source objects to be created and manipulated. The ADOX object model is shown in the following figure. Not all data sources support all of the objects in the model; this is determined by the specific OleDb Data Provider

The top-level object, Catalog, equates to a specific data source. This will almost always be a database, but specific OleDb Data Providers might expose different objects. The Groups and Users collections control access security for those data sources that implement it The Tables object represents the tables within the database. Each table contains a Columns collection, which represents individual fields in the table; an Indexes collection, which represents physical indexes. Create a Database Using ADOX 1. In the code editor, select makedbin the Control Name combo box, and then select Click in the Method Name combo box. In the code editor, select makedbin the Control Name combo box, and then select Click in the Method Name combo box. 1. In the form designer, double-click Make DB. Visual Studio adds the event handler to the code. 2. Add the following lines to the event handler, specifying the path to the Sample DBs directory on your system where indicated:

3. string dsStr, dsCN; 4. ADODB.Connection adcon = new ADODB.Connection(); 5. ADOX.Catalog mdb = new ADOX.Catalog(); 6. dsStr = "<<specify the path to the Sample DBs directory>>" _ 7. + "\\test.mdb"; 8. dsCN = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dsStr + ";"; 9. adcon.ConnectionString = dsCN; .10. mdb.Create(dsCN); 11. MessageBox.Show("Finished", "Make DB"); 12. Press F5 to run the application, and then click Make DB. Add a Table to a Database Using ADOX 1. In the code editor, select btnMakeTable in the Control Name combo box, and then select Click in the Method Name combo box. Visual Studio adds the event handler to the code. . In the form designer, double-click Make Table. Visual Studio adds the event handler to the code. 2. Add the following code to the event handler: 3. ADODB.Connection cnADO; 4. ADOX.Catalog mdb = new ADOX.Catalog(); 5. ADOX.Table dt = new ADOX.Table(); 6. cnADO = create_connection(); 7. cnADO.Open(cnADO.ConnectionString, "", "", -1); 8. mdb.ActiveConnection = cnADO; 9. dt.Name = "New Table";

10. dt.Columns.Append("TableID", ADOX.DataTypeEnum.adWChar, 5); 11. dt.Columns.Append("Value", ADOX.DataTypeEnum.adWChar, 20); 12. dt.Keys.Append("PK_NewTable", ADOX.KeyTypeEnum.adKeyPrimary, "TableID"); 13. mdb. Tables.Append(dt); 14. MessageBox.Show("Finished", "Make Table"); 15. Press F5 to run the application, and then click Make Table.

Connecting to MS Access Database in ASP .NET Code for Connecting to Access


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.OleDb; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Connection String OleDbConnection NewConnection = new OleDbConnection(@"Provider=Microsft.Jet.OLEDB.4.0; Data Source = c:\newDtabse.mdb"); NewConnection.Open(); //Connection Open } }

newDtabse.mdb is the name of database.

How to know about your OleDBConnection

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { OleDbConnection NewConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb"); NewConnection.Open(); Label1.Text = NewConnection.State.ToString(); Label2.Text = NewConnection.ServerVersion.ToString(); Label3.Text = NewConnection.Provider.ToString(); } }

emp_tbl table data show in a gridview.

Read Data from table using OleDBDataReader


protected void Page_Load(object sender, EventArgs e) { //Connection String OleDbConnection NewConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb"); NewConnection.Open();//Connection Open //Command Query OleDbCommand cmd = new OleDbCommand("Select * from emp_tbl", NewConnection); OleDbDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { GridView1.DataSource = dr; //Using GridView to Show the data. GridView1.DataBind(); } NewConnection.Close();// Connection Close }

To read data from Access database using an OleDbCommand object


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Connection String OleDbConnection NewConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb"); OleDbCommand cmd = NewConnection.CreateCommand();//Creating Command Object cmd.CommandText = "select * from emp_tbl";//Command Text NewConnection.Open();//Connection Open OleDbDataReader dr = cmd.ExecuteReader(); if (dr.HasRows)

} }

} NewConnection.Close();// Connection Close

GridView1.DataSource = dr; //Using GridView to Show the data. GridView1.DataBind();

ExecuteScaler

ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. If the Result Set is empty it will return a Null reference. It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { OleDbConnection NewConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source = D:\newDtabse.mdb"); OleDbCommand cmd = NewConnection.CreateCommand(); cmd.CommandText = "select count(*) from emp_tbl"; NewConnection.Open(); int count =(int)cmd.ExecuteScalar(); Label1.Text = count.ToString(); } }

Connecting to MS SQL Database in ASP .NET Creating a Connection


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open } }

How to know about your SqlConnection


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open Label1.Text = newConnection.State.ToString(); Label2.Text = newConnection.ServerVersion.ToString(); newConnection.Close();// Connection Close } }

Read Data from Database using SqlDataReader


public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open //Command Query SqlCommand cmd = new SqlCommand("Select * from emp_tbl", newConnection); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { GridView1.DataSource = dr; //Using GridView to Show the data. GridView1.DataBind(); } newConnection.Close();// Connection Close } }

Using SqlDataAdapter Fill the GridView


protected void Page_Load(object sender, EventArgs e) { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); newConnection.Open();//Connection Open SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl",newConnection); DataSet ds = new DataSet(); ad.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); }

How To Update a Grid View Value Using Procedure in ASP .NET


Step 1: First creating a Stored Procedure using SQL Server. Procedure name as empDetails CREATE PROCEDURE empDetails @name nchar(10), @id nchar(10), @emp_age nchar(10) AS BEGIN UPDATE emp_tbl SET nme = @name, age = @emp_age WHERE emp_id = @Id END Step 2. Design the page. Take a Grid View Control to show data and three textboxes and a button.
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body><form id="form1" runat="server"> <div><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderStyle="Solid" > <RowStyle BackColor="White" BorderColor="#333333" BorderStyle="Solid" BorderWidth="2px" /> <Columns><asp:BoundField DataField="nme" HeaderText="Name" /> <asp:BoundField DataField="age" HeaderText="Age" />

<asp:BoundField DataField="emp_id" HeaderText="Employe ID" /> </Columns><HeaderStyle BackColor="#CCCCCC" BorderStyle="Inset" BorderWidth="2px" /> </asp:GridView> </div> <br /><br /> <table> <tr><td>Enter ID(From Grid View):</td><td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td></tr> <tr><td>Enter Name:</td><td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td></tr> <tr><td>Enter Age:</td><td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td></tr> <tr><td> <asp:Button ID="Button1" runat="server" Text="Update" onclick="Button1_Click" /> ]</td></tr> </table> </form> </body> </html>

Step 3.Default.aspx.cs Code.


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\ SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmdd = new SqlCommand("Select * from emp_tbl", newConnection); SqlDataReader dr = cmdd.ExecuteReader(); if (dr.HasRows) { GridView1.DataSource = dr; GridView1.DataBind(); } newConnection.Close();

} public void update_value(string emp_name, string Id, string emp_age) { newConnection.Open(); SqlCommand cmd = new SqlCommand("empDetails",newConnection); cmd.CommandType = CommandType.StoredProcedure; //Procedure cmd.Parameters.AddWithValue("@name", emp_name); cmd.Parameters.AddWithValue("@id", Id); cmd.Parameters.AddWithValue("@emp_age", emp_age); cmd.ExecuteNonQuery(); newConnection.Close(); } protected void Button1_Click(object sender, EventArgs e) { //call the function to updating the grid view update_value(TextBox2.Text,TextBox1.Text,TextBox3.Text); }

Step 4: Run the Application.

Click the Update Button

Insert a Data in Database using Procedure in ASP .NET


Step 1: First creating a Stored Procedure using SQL Server. Procedure name as AddEmpDetails CREATE PROCEDURE AddEmpDetails @name nchar(10), @id nchar(10), @emp_age nchar(10) AS BEGIN INSERT INTO emp_tbl(nme,age,emp_id) VALUES (@name,@emp_age,@id) END Step 2. Design the page. Take a Grid View Control to show data and three textboxes and a button.
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body><form id="form1" runat="server"> <div><asp:GridView ID="GridView1" runat="server"

AutoGenerateColumns="False" BorderStyle="Solid" > <RowStyle BackColor="White" BorderColor="#333333" BorderStyle="Solid" BorderWidth="2px" /> <Columns><asp:BoundField DataField="nme" HeaderText="Name" /> <asp:BoundField DataField="age" HeaderText="Age" /> <asp:BoundField DataField="emp_id" HeaderText="Employe ID" /> </Columns><HeaderStyle BackColor="#CCCCCC" BorderStyle="Inset" BorderWidth="2px" /> </asp:GridView> </div> <br /><br /> <table> <tr><td>Enter ID:</td><td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td></tr> <tr><td>Enter Name:</td><td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td></tr> <tr><td>Enter Age:</td><td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td></tr> <tr><td> <asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" /> </td></tr> </table> </form> </body> </html>

Step 3.Default.aspx.cs Code.


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmdd = new SqlCommand("Select * from emp_tbl", newConnection); SqlDataReader dr = cmdd.ExecuteReader(); if (dr.HasRows) {

GridView1.DataSource = dr; GridView1.DataBind(); } newConnection.Close(); } public void addValue(string emp_name, string Id, string emp_age) { newConnection.Open(); SqlCommand cmd = new SqlCommand("AddEmpDetails", newConnection); cmd.CommandType = CommandType.StoredProcedure; //Procedure cmd.Parameters.AddWithValue("@name", emp_name); cmd.Parameters.AddWithValue("@id", Id); cmd.Parameters.AddWithValue("@emp_age", emp_age); cmd.ExecuteNonQuery(); newConnection.Close(); } protected void Button1_Click(object sender, EventArgs e) { addValue(TextBox2.Text, TextBox1.Text, TextBox3.Text); Response.Redirect("Default.aspx"); } }

Step 4: Run the Application.

Click on Add button.

The Value is added in the database

How to Get all Information SQL Server in ASP .NET


Step 1. Drag a text Box and a Button control on your page. Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <table><tr> <td>Enter the ID:</td><td>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td><td> <asp:Label ID="Label1" runat="server"></asp:Label> </td></tr> <tr><td> <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" /></td></tr> </table> </div> </form> </body> </html>

Step 2. Default.aspx.cs Code


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmd = new SqlCommand("select age,nme from emp_tbl where emp_id=@id", newConnection); cmd.Parameters.AddWithValue("@id", TextBox1.Text); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Label1.Text = "Employee Name: " + dr["nme"].ToString() + " and Your age is " + dr["age"].ToString(); } else { Label1.Text = "Enter Correct Emp ID"; } }

Step 3. Run the Application.

Retrieving Data Using a SQL Server Stored Procedure IN ASP.NET


Step 1. The Design Code is:
<%@ Page Language="C#" AutoEventWireup="true" Codevirtual="Default.aspx.cs" Inherits="_Default" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body><form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderStyle="Solid" BorderWidth="2px" Height="86px" Width="258px" > <RowStyle BackColor="White" BorderColor="#333333" BorderStyle="Solid" BorderWidth="2px" /> <Columns><asp:BoundField DataField="nme" HeaderText="Name" /> <asp:BoundField DataField="age" HeaderText="Age" /> <asp:BoundField DataField="emp_id" HeaderText="Employe ID" /> </Columns> <SelectedRowStyle BorderStyle="Solid" /> <HeaderStyle BackColor="#CCCCCC" BorderStyle="Inset" BorderWidth="2px" /> <EditRowStyle BorderStyle="Solid" BorderWidth="2px" /> </asp:GridView> </div> <br /><br /> </form> </body> </html>

Stored Procedure: CREATE PROCEDURE SelectEmpDetails @id nchar(10) AS BEGIN SELECT * FROM emp_tbl WHERE emp_ID=@id END Step 2. Default.aspx.cs Code
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmdd = new SqlCommand("SelectEmpDetails", newConnection); cmdd.CommandType = CommandType.StoredProcedure; cmdd.Parameters.Add("@id", SqlDbType.Int).Value = 1234; SqlDataReader dr = cmdd.ExecuteReader(); if (dr.HasRows) { GridView1.DataSource = dr; GridView1.DataBind(); } newConnection.Close(); } }

Out Put:

Build SqlConnectionStringBuilder from connection string


Provides a simple way to create and manage the contents of connection strings used by the SqlConnection class. Property: 1. ApplicationName 2. AsynchronousProcessing 3. AttachDBFilename 4. BrowsableConnectionString 5. ConnectionReset 6. ConnectionString 7. ConnectTimeout 8. ContextConnection 9. CurrentLanguage 10. DataSource 11. FailoverPartner 12. InitialCatalog 13. IntegratedSecurity 14. IsFixedSize 15. IsReadOnly 16. LoadBalanceTimeout 17. MaxPoolSize 18. MinPoolSize 19. MultipleActiveResultSets 20. NetworkLibrary 21. PacketSize 22. PersistSecurityInfo 23. TransactionBinding 24. System.Transactions

25. TrustServerCertificate 26. TypeSystemVersion 27. UserID 28. UserInstance 29. WorkstationID
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { string conString=@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true; Min Pool Size=5;Max Pool Size=15;Connection Reset=True; Connection Lifetime=600;"; protected void Page_Load(object sender, EventArgs e) { SqlConnectionStringBuilder sub = new SqlConnectionStringBuilder(conString); Response.Write("Parsed SQL Connection String Parameters:"); Response.Write(" Database Source = " + sub.DataSource); Response.Write(" Database = " + sub.InitialCatalog); Response.Write(" Use Integrated Security = " + sub.IntegratedSecurity); Response.Write(" Min Pool Size = " + sub.MinPoolSize); Response.Write(" Max Pool Size = " + sub.MaxPoolSize); Response.Write(" Lifetime = " + sub.LoadBalanceTimeout); Response.Write(" Connection Reset = " + sub.ConnectionReset); } }

How To Build a connection string from component parameters and display It.
using using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { SqlConnectionStringBuilder sub = new SqlConnectionStringBuilder(); sub.DataSource =@"\SQLEXPRESS"; sub.InitialCatalog = "newDatabase"; sub.IntegratedSecurity = true; sub.MinPoolSize = 5; sub.MinPoolSize = 15; sub.LoadBalanceTimeout = 600; sub.ConnectionReset = true; Response.Write("" + sub.ConnectionString); } }

Out Put:

Executing a Parameterized Query with SqlCommand in ASP. NET


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;");

protected void Page_Load(object sender, EventArgs e) { SqlCommand sqlCommand = new SqlCommand("select * from emp_tbl where emp_id > @id",newConnection); sqlCommand.Parameters.Add("@id", SqlDbType.Int).Value=123; SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand); DataTable sqlDt = new DataTable(); sqlDa.Fill(sqlDt); foreach (DataRow row in sqlDt.Rows) { Response.Write(row["nme"]); Response.Write(row["emp_id"]); Response.Write(row["age"]); } } }

Out Put:

How to execute multiple SQL statements using a SqlCommand object


using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("insert into emp_tbl (nme,age,emp_id) values ('atul', '24','1234');" + "select nme,age from emp_tbl where emp_id=1234 "+ "update emp_tbl set nme='Anjali' where emp_id=1234" + "select nme,age from emp_tbl where emp_id=1234 ;",newConnection); newConnection.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { GridView1.DataSource = dr; GridView1.DataBind(); } newConnection.Close(); } }

Out Put:

How to Get Table Information in ASP .NET


using System; using System.Configuration;

using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("SELECT TABLE_TYPE, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", newConnection); newConnection.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Label1.Text ="Table Type: "+dr[0].ToString(); Label2.Text = "Table Name: "+dr[1].ToString(); } newConnection.Close(); } }

Out Put:

How to update a table data in GridView Control Using C#


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) bindData(); } public void bindData() { SqlCommand cmd = new SqlCommand("select * from emp_tbl", newConnection); newConnection.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { GridView1.DataSource = dr; GridView1.DataBind(); } newConnection.Close(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bindData(); } protected void Button1_Click(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmdd = new SqlCommand("update emp_tbl set nme=@a,age=@b where emp_id='"+TextBox3.Text+"'",

newConnection); cmdd.Parameters.Add("@a",TextBox1.Text); cmdd.Parameters.Add("@b", TextBox2.Text); cmdd.ExecuteNonQuery(); newConnection.Close(); bindData(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string s = GridView1.DataKeys[e.RowIndex].Value.ToString(); newConnection.Open(); SqlCommand cmdd = new SqlCommand("select * from emp_tbl where emp_id='" + s + "'", newConnection); SqlDataReader dr1 = cmdd.ExecuteReader(); if (dr1.Read()) { TextBox1.Text = dr1["nme"].ToString(); TextBox2.Text = dr1["age"].ToString(); TextBox3.Text = dr1["emp_id"].ToString(); } newConnection.Close(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bindData(); } }

Out Put: Click on the Edit Button which row you want to update.

Click on the Update Button.

Edit your Values and click on Update, value is Updated.

Inserts (Create) a new table in ASP .Net using C#


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlCommand cmd = new SqlCommand("create table Emp_Login (UserName nvarchar(20), Password

nvarchar(20))"+ "insert into Emp_Login (UserName,Password) values ('atul','1234');", newConnection); cmd.ExecuteNonQuery(); newConnection.Close(); } }

Out Put:

Insert Data using SqlCommandBuilder in ADO.NET using C#


SqlCommandBuilder: This enables you to UPDATE database tables without having to write the commands, reducing the likelihood of errors. This class cannot be inherited.
using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts;

using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl", newConnection); SqlCommandBuilder cmd = new SqlCommandBuilder(ad); DataSet ds = new DataSet(); ad.Fill(ds); DataRow MyRow = ds.Tables[0].NewRow(); MyRow["emp_id"] = 1234; MyRow["emp_name"] = "Anjali"; MyRow["emp_age"] = "25"; ds.Tables[0].Rows.Add(MyRow); ad.Update(ds); } }

Out Put:

Using SqlCommandBuilder show SQL statement


using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { SqlConnection newConnection = new SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; initial catalog=newDatabase;integrated security=true;"); protected void Page_Load(object sender, EventArgs e) { newConnection.Open(); SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl", newConnection); SqlCommandBuilder cmd = new SqlCommandBuilder(ad); Label1.Text = "SQL Select Command is: " + ad.SelectCommand.CommandText; SqlCommand updateCommand = cmd.GetUpdateCommand(); Label2.Text="SQL Update Command is: " +updateCommand.CommandText; SqlCommand insertCommand = cmd.GetInsertCommand(); Label3.Text="SQL Insert Command is: " +insertCommand.CommandText; SqlCommand deleteCommand = cmd.GetDeleteCommand(); Label4.Text="SQL Delete Command is: " +deleteCommand.CommandText; } }

Out Put:

ADO.net Interview Questions And Answers

Page 1
Ques: 1 Why ADO.NET? Ans: ADO.NET is data access layer Ans: We create a connection for database after that we queried the information from database. Ans: Data Provider is a set of components including: 1.The Connection object (SqlConnection, OleDbConnection, OdbcConnection, OracleConnection) 2.The Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand) 3.The DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader) 4.The DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter). DataSet object represents a disconnected cache of data which is made up of DataTables and DataRelations that represent the result of the command. Ques: 2 What is full name of ADO.NET? Ans: ActiveX Data Objects Ques: 3 Give Short History of ADO.Net.

Ans: Microsoft developed ActiveX Data Objects (ADO) as a COM( Component Object Model ) wrapper around OLE DB for Databases. Ques: 4 Why ADO.NET Is a Better Data Access Layer than others? Ques: 5 Write a sample example of ADO.Net? Ans: using System; using System.Data; using System.Data.OleDb; // Step 1.Open Database Connection OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\inventory\\inventory\\db\\invent.mdb;"); // Step 2.Connection database opened conn.Open(); // Step 3.Create DataSet and Command objects OleDbCommand cmd = new OleDbCommand( "SELECT * FROM empr4r", conn); // Step 4.Execute the command cmd.ExecuteScalar(); // Step 5.Closed this connection conn.Close(); Ans: using System; using System.Data; using System.Data.OleDb; // Step 1.Open Database Connection OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\inventory\\inventory\\db\\invent.mdb;"); // Step 2.Connection database opened conn.Open(); // Step 3.Create DataSet and Command objects OleDbCommand cmd = new OleDbCommand( "SELECT * FROM empr4r", conn); // Step 4.Execute the command cmd.ExecuteScalar(); // Step 5.Closed this connection conn.Close(); Ques: 6 Explain ADO.NET Namespaces? Ans: The System.Data is main namespace of ADO.Net and it has DataSet and classes (DataTable, DataColumn, DataRow, DataRelation, Constraint,etc ). System.Data has a namespace System.Data.Common.

Ques: 7 What is ADO.NET Data Structures? Ans: ADO.NET has three different ways of accessing database information directly which are: 1.Commands :-have classes SqlCommand and OleDbCommand , used directly to retrieve results from database queries.Command classes always support the IDbCommand interface.Commands classesare used to get a scalar result (the first column of the first row of a result set) or out parameters of a stored procedure.sort of data is retrieved using IDbCommand.ExecuteScalar() and IDbCommand.ExecuteNonQuery() 2.DataReaders has SqlDataReader and OleDbDataReader.These classes are provide something similar to ADO's Recordset using a forward-only cursor. 3.DataSets classes Microsoft uses DataReaders within the managed providers' DataAdapters to fill DataSet Ques: 8 Define ADO.NET provides data access services in the Microsoft .NET platform? Ans: ADO.NET to access data by using the new .NET Framework data providers which are given below: 1.Data Provider for SQL Server (System.Data.SqlClient) 2.Data Provider for OLEDB (System.Data.OleDb) 3.Data Provider for ODBC (System.Data.Odbc). 4.Data Provider for Oracle (System.Data.OracleClient). Ques: 9 Tell me about ADO.NET Classes? Ans: The ADO.NET classes are found in System.Data.dll and are integrated with the XML classes in System.Xml.dll. ADO.NET is a set of classes that expose data access services to the .NET developer. There are two central components of ADO.NET classes: the DataSet, and the .NET Framework Data Provider. Ques: 10 Define Data Provider in ADO.NET? Ans: Data Provider is a set of components including: 1.The Connection object (SqlConnection, OleDbConnection, OdbcConnection, OracleConnection) 2.The Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand) 3.The DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader) 4.The DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter). DataSet object represents a disconnected cache of data which is made up of DataTables and DataRelations that represent the result of the command. Ques: 11 Define Dataset in ADO.Net? Ans: Dataset is: 1.Disconnected Recordset objects similar to an array. 2.Supports disconnected data access and operations. 3.Scalability, Provide greater scalability because users no longer have to be connected to the database all the time. DataSet object is made up of two objects: 1.DataTableCollection object containing null or multiple DataTable objects 2.DataRelationCollection object containing null or multiple DataRelation objects which establish a parent/child relation between two DataTable objects. Ques: 12 Define types of Datasets in ADO.Net?

Ans: There are two type of dataset in Ado.net: 1.Typed DataSet: Typed DataSet is derived from the base DataSet class and then uses information in an XML Schema file (.xsd file) in order to generate a new class. Create a typed DataSet without designer - manually a.Call the command prompt (cmd) at the location of the XSD schema file. b.Use the XSD.EXE utility to create the class for the typed DataSet. 2.Untyped DataSet : Untyped DataSet is not defined by a schema, instead, you have to add tables, columns and other elements to it yourself, either by setting properties at design time or by adding them at run time. Ques: 13 Define the ways to populate a Dataset in ADO.Net? Ans: There are following way to populate Dataset: a.By using DataAdapter objects and Fill method. b.By creating DataTable, DataColumn and DataRow objects programmatically. c.Read an XML document or stream into the DataSet. d.Merge (copy) the contents of another DataSet, with the Merge method. Ques: 14 Define DataAdapter in ADO.Net? Ans: DataAdapter object is links the database and a Connection object with the ADO.NET-managedDataSet object through its SELECT and action query Commands. Means it works like a bridge DataAdapter specified that which data is to move into and out of the DataSet. DataAdapter provide references to SQL statements or stored procedures that are invoked to read or write to a database. The DataAdapter provides four properties that allow us to control how updates are made to the server: SelectCommand UpdateCommand InsertCommand DeleteCommand Ques: 15 Define methods of DataAdapter in ADO.Net? Ans: The DataAdapter includes three main methods: 1.Fill (populates a DataSet with data). 2.FillSchema (queries the database for schema information that is necessary to update). 3.Update (to change the database, DataAdapter calls the DeleteCommand, the InsertCommand and the UpdateCommand properties). Ques: 16 How to DataBindings for TextBoxes in ADO.Net? Ans: To bind some elements of a data source with some graphical elements of an application, this ability known as DataBinding. The data in Windows Forms is bound by calling DataBindings. Windows Forms allows you to bind easily to almost any structure that contains data. Windows Forms Controls support two types of data binding: a.Simple Data Binding: To display a single data element, means to display a column value from a DataSet table, in a control. It is possible to bind any property of a control to a given data value. Simple Data Binding can be performedby two ways: 1.At design time using DataBindings property of a control 2.Dynamically at run time. This is the type of binding typical for controls such as a TextBox control or Label control that displays typically only a single value.

b.Complex Data Binding: To bind more than one data element, typically more than one record in a database, or to more than one of any other type of bindable data element. DataGrid, ListBox and ErrorProvider controls support complex data binding. Ques: 17 Define ADO.NET Objects in brief? Ans: ADO.net includes many objects you can use to work with data. Some of the primary objects are: 1. The SqlConnection Object 2. The SqlCommand Object 3. The SqlDataReader Object 4. The DataSet Object 5. The SqlDataAdapter Object Ques: 18 How to Create a SqlConnection Object in Ado.Net? Ans: SqlConnection object is like a c# object.The object declare like that: SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); This argument is called a connection string. It is define as: Data Source: Identifies the server. Integrated Security: Set to SSPI to make connection with user's Windows login User ID: Name of user configured in SQL Server. Password: Password matching SQL Server User ID. Using a SqlConnetion the connection creates as: 1.Instantiate the SqlConnection. 2.Open the connection. 3.Pass the connection to other ADO.NET objects. 4.Perform database operations with the other ADO.NET objects. 5.Close the connection. Ques: 19 How to create a SqlCommand Object in ADO.Net? Ans: SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); Above syntax is written to instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. Ques: 20 How to querying in ADO.Net, when using SqlCommand? Ans: Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); Call Execute reader to get query results SqlDataReader rdr = cmd.ExecuteReader(); Passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd.

ADO.net Interview Questions And Answers

Page 1
Ques: 1 Define methods provided by the dataset object to generate XML in ADO.Net? Ans: 1.ReadXML: Reads a XML document in to Dataset. 2.GetXML: This is a function, which returns the string containing XML document.

3.Writexml: This writes a XML data to disk. Ques: 2 Define Connection Pooling in brief? Ans: Connection Pooling make a single connection instance, which allows that instance to connect to all the databases. It does not open and close the connection object multiple times. Ques: 3 Difference between classic ADO and ADO.NET? Ans: 1.We have recordset in ADO and in ADO.NET we have dataset. 2.In recordset we can only have one table. If we want to accommodate more than one table we need to do inner join and fill the recordset. Dataset can have multiple tables. 3.All data persist in XML as compared to classic ADO where data persisted in Binary format also. Ques: 4 Explain the difference between an ADO.NET Dataset and an ADO Recordset? Ans: 1.Using dataset retrieve data from two databases like Oracle and SQL server and merge them in one dataset, with recordset this is not possible. 2.Recordset uses COM. But all representation of Dataset is using XML. 3.Dataset can be transmitted on HTTP while Recordset cannot be transmitted. Ques: 5 Define, how can we load multiple tables in a Dataset? Ans: objCommand.CommandText = "Tab1" objDataAdapter.Fill(objDataSet, "Tab1") objCommand.CommandText = "Tab2" objDataAdapter.Fill(objDataSet, "Tab2") Above code shows how to load multiple Data Table objects in one Dataset object. Sample code shows two tables Tab1 and Tab2 in object ObjDataSet. lstdata.DataSource = objDataSet.Tables("Tab1").DefaultView In order to refer Tab1 Data Table, use Tables collection of Datasets and the Default view object will give you the necessary output. Ques: 6 What is the difference between Dataset and DataReader? Ans: 1.To cache data and pass to a different tier Dataset forms the best choice and it has decent XML support 2.Dataset is a disconnected architecture; DataReader has live connection while reading data. 3.To access data from more than one table Dataset forms the best choice. 4.If we need to move back while reading records, data reader does not support this functionality. 5.A biggest drawback of Dataset is speed. As Dataset carry considerable overhead because of relations, multiple table etc speed is slower than DataReader. Always try to use DataReader wherever possible, as it is meant especially for speed performance. Ques: 7 Compare the Connection-Oriented and Disconnected Scenario in ADO.Net? Ans: Connection-Oriented Scenario: 1.Always accessing current data 2.Low number of concurrent data accesses 3.Many write accesses situation 4.IDbConnection, IDbCommand, IDataReader Disconnected Scenario:

1.Modification in Dataset is not equal to modification in data source 2.Many concurrent read accesses situation 3.Dataset, Data table, DbDataAdapter Ques: 8 What are the basic Namespaces in ADO.Net? Ans: Some basic namespaces are: 1.System.Data (basics types) 2.System.Data.OleDb (OLEDB Provider) 3.System.Data.SqlClient (Microsoft Sql Server provider) 4.System.Data.Common 5.System.Data.SqlTypes 6.System.Data.Odbc (ODBC Provider) 7.System.Data.Odbc.OracleClient (Oracle Provider) 8.System.Data.SqlServerCe (Compact framework) Ques: 9 How to Filling the DataSet in Disconnected mode in ADO.Net? Ans: Once you have a DataSet and SqlDataAdapter instances, you need to fill the DataSet. Here's how to do it, by using the Fill method of the SqlDataAdapter: SqlDataAdapter daStudent = new SqlDataAdapter ("select StudentID, CollegeName from Students", conn); SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daStudent); daStudent.Fill(dsStudent, "Students"); Fill method, takes two parameters: a DataSet and a table name. Ques: 10 How to create a SqlDataAdapter in ADO.Net? Ans: SqlDataAdapter holds the SQL commands and connection object for reading and writing data. It initializes with a SQL select statement and connection object: SqlDataAdapter daStudent = new SqlDataAdapter( "select StudentID, CollegeName from Students", conn); The SQL select statement specifies what data will be read into a DataSet. The connection object, conn, should have already been instantiated, but not opened. SqlCommandBuilder is instantiated with a single constructor parameter of the SqlDataAdapter, daStudent, instance. SqlCommandBuilder cmdBldr = new SqlCommandBuilder(daStudent); SqlCommandBuilder will read the SQL select statement (specified when the SqlDataAdapter was instantiated), infer the insert, update, and delete commands. Ques: 11 How to Create a DataSet Object in ADO.Net? Ans: Dataset object create as: DataSet dsStudents = new DataSet(); DataSet constructor doesn't require parameters. However there is one overload that accepts a string for the name of the DataSet, which is used if you were to serialize the data to XML. Since that isn't a requirement for this example, I left it out. Right now, the DataSet is empty and you need a SqlDataAdapter to load it. Ques: 12 How to Read data with SqlDataReader Object in ADO.Net? Ans: SqlDataReader rdr = cmd.ExecuteReader(); The typical method of reading from the data stream returned by the SqlDataReader is to iterate through each row with a while loop. while (rdr.Read()) { string conta = (string)rdr["ContactName"];

string comp = (string)rdr["CompanyName"]; string cty = (string)rdr["City"]; Console.Write("{0,-25}", conta); Console.Write("{0,-20}", cty); Console.Write("{0,-25}", comp); Console.WriteLine(); } Ques: 13 How to create a SqlDataReader Object in ADO.Net? Ans: There is a little different way to creating object of a SqlDataReader like other object creation in C#. Necessary call ExecuteReader on a command object. SqlDataReader rdr = cmd.ExecuteReader(); The ExecuteReader method of the SqlCommand object, cmd , returns a SqlDataReader instance. Ques: 14 How to Deleting Data when using SqlCommand Object in ADO.Net? Ans: To deleting data also using the ExecuteNonQuery method. The following example shows how to delete a record from a database with the ExecuteNonQuery method: 1.Prepare command string 2.Instantiate a new command SqlCommand cmd = new SqlCommand(); 3.Set the CommandText property cmd.CommandText = deleteString; 4.Set the Connection property cmd.Connection = conn; 5.Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Ques: 15 How to Updating Data when using SqlCommand Object in ADO.Net? Ans: The ExecuteNonQuery method is also used for updating data. The following code shows how to update data: 1.Prepare command string 2.Instantiate a new command with command text only SqlCommand cmd = new SqlCommand(updateString) 3.Set the Connection property cmd.Connection = conn; 4.Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Ques: 16 How to Inserting Data when using SqlCommand Object in ADO.Net? Ans: To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object. Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand(insertString, conn); Call ExecuteNonQuery to send command cmd.ExecuteNonQuery(); Ques: 17 How to querying in ADO.Net, when using SqlCommand? Ans: Instantiate a new command with a query and connection SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); Call Execute reader to get query results SqlDataReader rdr = cmd.ExecuteReader();

Passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd. Ques: 18 How to create a SqlCommand Object in ADO.Net? Ans: SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn); Above syntax is written to instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. Ques: 19 How to Create a SqlConnection Object in Ado.Net? Ans: SqlConnection object is like a c# object.The object declare like that: SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); This argument is called a connection string. It is define as: Data Source: Identifies the server. Integrated Security: Set to SSPI to make connection with user's Windows login User ID: Name of user configured in SQL Server. Password: Password matching SQL Server User ID. Using a SqlConnetion the connection creates as: 1.Instantiate the SqlConnection. 2.Open the connection. 3.Pass the connection to other ADO.NET objects. 4.Perform database operations with the other ADO.NET objects. 5.Close the connection. Ques: 20 Define ADO.NET Objects in brief? Ans: ADO.net includes many objects you can use to work with data. Some of the primary objects are: 1. The SqlConnection Object 2. The SqlCommand Object 3. The SqlDataReader Object 4. The DataSet Object 5. The SqlDataAdapter Object

Potrebbero piacerti anche