• Save
Ado.net
Upcoming SlideShare
Loading in...5
×
 

Ado.net

on

  • 3,518 views

 

Statistics

Views

Total Views
3,518
Slideshare-icon Views on SlideShare
3,518
Embed Views
0

Actions

Likes
5
Downloads
0
Comments
2

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

12 of 2

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Could you please mail me this presentation?
    Are you sure you want to
    Your message goes here
    Processing…
  • Can I get the presentation pls?
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • The DataReader was developed to get at data and in read-only forward-only fashion and provide the data as fast as possible to enable the developers as fast as possible. With the help of DataSet, it takes a snapshot of the data from database and storing this data offline for as long as necessary. When the end user using this copy of data he can persist the data and any changes to the data right back to data store.
  • Among the above 6 core namespaces ADO.NET classes are divided into three categories: Disconnected : These classes provides basic structure of ADO.NET includes DataTable, etc., The objects of this class are capable of storing data without any dependency on specific data provider. Shared: Set of base classes for data providers and shared among all data providers. Includes DataSet, DataRow, DataTable, Constraint, etc., Data Providers: These classes are meant to work with different data sources. Performs all database management operations on a specific database. Eg: SqlClient data provider works only with SQL Server Database.
  • ADO.NET ships with four database client namespaces. They are: System.Data.SqlClient System.Data.OracleClient System.Data.OleDb System.Data.Odbc. Within the .NET Framework data providers are light weight, creating minimal layer between the data source and code, increasing performance without scarifying functionality.
  • The SqlConnection Properties the DataSource, Database and State are read-only properties to read database server , database name and state of connection respectively.
  • Calling a stored procedure with a Command object is just assigning the stored procedure name to CommandText property of SqlCommand instance also setting the CommnadType property to CommandType.StoredProcedure value. Finally execute the one of previously stated method. The default ComandTimeout value is 30 seconds. The SqlRecord object contains only single returned row. When you begin transaction you can choose isolation level for commands executed within that transaction. This isolation levels specifies how changes made in one database session are viewed by another. These isolation levels are: ReadCommitted ReadUncomitted RepeatableRead Serializable ExecuteNonQuery() method is commonly user for UPDATE, INSERT or DELETE statements: This call will returns only the number of records effected. This call however can return results if you call a stored procedure that has output parameters.
  • While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
  • While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
  • SelectCommand: Gets or sets an object of type SqlCommand . This command is automatically executed to fill a DataTable with the result set. InsertComand: Gets or sets an object of type SqlCommand . This command used automatically executed to insert a new record to the database. UpdateCommand: Gets or sets an object of type SqlCommand . This command used to update the existing record on database. DeleteCommand: Gets or sets an object of type SqlCommand . Used to delete an existing record on database.
  • ParameterName: Gets or sets the name of the parameter SqlDbType: SQL server database type of the parameter value Size: Gets or sets the size of the parameter value. Direction: Gets or sets the direction of parameter such as input, output, or InputOutput . SourceColumn: Maps a column from a DataTable to the parameter. It enables you to execute multiple commands from SqlDataAdapter object and pick the correct parameter value from a DataTable column during the command execution. Value : Sets or gets the value provided by the parameter object. This value passed to the parameter defined in the command during the runtime.
  • Here links means primary key and Foreign key relation ships etc., In the above DataColumn instance we have given column name to CustomerID . If we don’t give there will be auto-generated column name(1, 2, .., ) is assigned by runtime. DataRow versions are described as: Current : The value existing at present column within the column. If no edit has occurred since received from database then it will be same as original value. Default: The default value. Original: The value of the column when originally selected from database. Proposed: When changes are proposed for a row it is possible to retrieve this modified value. (In between BeginEdit() and EndEdit() methods). Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet .
  • Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet . Server Explorer : In visual studio menu items select Data  Generate Data Set;; It will creates Connection, adapter and xsd files. Using the DataAdapter : Open a connection Create a DataAdapter Finally Fill DataSet. To create DataSet programmatically: Define data column object Add DataColumn object to a DataTable Add DataTable object to a DataSet
  • If you select data from database and populating it with adapter class runtime automatically creates the schema for your DataTable. It is also possible to create a DataTable programmatically. So creating schemas programmatically. Finally .NET framework also supports for using XML schemas to define a DataSet class, DataTable class and other classes. In the above relationships means Primary key and Foreign key relationship between the columns of different tables. The key difference between DataSet class and old style hierarchical Recordset object is in the way relationship is presented. In Recordset object the relationship was presented was a pseudo-column within the row. This column itself was a Recordset object. The below constrains are enforced within a DataSet class if the EnforcedConstraints property of the DataSet is true. Cascade: If the parent key has been updated copy new key value to all child records. If the parent record has been deleted then delete all the child records also. None: No action in child records whatsoever. This option leaves orphand rows within the child data table. SetDefault: Each child record affected has the foreign key column set to its default value if one has defined. SetNull: All child rows have the key column set to DBNull.
  • If you are working on a single table just use DataTable instead of DataSet. If you are working with multiple table and you need container for those tables to make relations use DataSet . To load the data from DataReader to DataTable just call Load() method on DataTable . SqlDataReader myReader = cmd.ExecuteReader(..); DataTable myTable = new DataTable(); myTable.Load(myReader); In reverse if you want a reader from DataTable then use: DataTableReader myReader = myTable.CreateDataReader();
  • From the early .Net have DataGrid control. But it have many draw backs such as can’t display images, can’t accommodate drop down control, or can’t lock columns etc., But with .NET DataGridView addresses all these problems. The AutoGenerateColumns property specifies whether the columns to create automatically when DataSource or DataMember is set. If you set to false you need to create all columns manually. The property DataSource gets or sets the data source for which the system displaying the data. The property DataMember gets or set the name of the list or table in the data sources for which DataGridView is displaying data.
  • If you want to display combo box for any particular column then you need to create columns yourself by setting AutoGeneratedColumn property to false.
  • All the Data Source Controls are derived from DataSourceControl class which it self derived from Control class and implements IDataSource and IListSoucre interfaces. You can use them as you would use any Web Server Control. All data source controls share basic set of core functionality. The SqlDataSource Control provides access to any data source that has ADO.NET data provider available. It has access to ODBC, OLEDB, SQL Server, Oracle, SQL Server CE providers. The SiteMapDataSource Control provides access to sitemap data for a web site that is stored by the sitemap provider. If your SQL query requires parameters to pass ASP.NET defines several parameter types: All are derived from Parameters class. ControlParameter CookieParameter FormParameter QueryStringParameter ( Used with SQL queries). ProfileParameter SessionParameter.
  • With ASP.NET you can bind the data to a lot of databound controls: GridView, PageView, DrowDownList, ListBox, etc.,

Ado.net Ado.net Presentation Transcript

  • Introducing ADO.NET by Rajini K
  • Introduction
    • Acronym for ActiveX Data Objects
    • ADO.NET is the successor to Microsoft’s ADO technology
    • Both provided consistent, high-performance access to data
  • What is ADO.NET?
    • The acronym of ADO.NET is ActiveX Data Object .
    • ADO.NET is the data-access technology that enables applications to connect to data stores and manipulate data contained in them in various ways.
    • It is based on the .NET framework and it is highly integrated with the rest of the framework class library.
    • ADO.NET is a collection of classes, interfaces, structures, enumerated types that manage data access from the relational data stores within the .Net framework
  • Working with ADO.NET
    • Many of Web application development, in many of the developers data situations involves opening data store, making request for specific data, and then populating the table in the browser with the data.
    • To address the above situations ADO.NET supports the following classes:
      • DataReader
      • DataSet
  • ADO.NET Architecture
  • SQL Managed Provider SQL Server Database ADO.NET Managed Provider ADO Managed Provider OLE DB Provider Database Your Application
  • Working with ADO.NET namespaces
    • The six core ADO.NET namespaces are:
      • System.Data
      • System.Data.Common
      • System.Data.OleDb
      • System.Data.Odbc
      • System.Data.SqlClient
      • System.Data.SqlTypes
    • The classes from the above namespaces are categorized as follow:
      • Disconnected : These classes provides basic structure of ADO.NET includes DataTable, etc.,. The objects of this class are capable of storing data without any dependency on specific data provider.
      • Shared: Set of base classes for data providers and shared among all data providers. Includes DataSet, DataRow, DataTable, Constraint, etc.,
      • Data Providers: These classes are meant to work with different data sources. Performs all database management operations on a specific database.
        • Eg: SqlClient data provider works only with SQL Server Database.
  • Data Providers Classes
    • In .NET Framework data provider is used for connecting to database, executing commands are retrieving results. By default the following data provides are included in .NET Framework:
      • Data Provider for SQL Server
      • Data Provider for OLEDB
      • Data Provider for ODBC
      • Data Provider for Oracle.
    • In .NET to access the data set of classes defined in the namespaces System.Data and other namespaces defined within this namespace.
    • Each data provider contains the following objects:
      • Connection ( Eg: SqlConnection, OracleConnection, OdbcConnection, etc., )
      • Comnand, CommandBuilder ( Eg: SqlCommand, SqlComandBuilder, etc., )
      • DataAdapter ( Eg: SqlDataAdapter, etc., )
      • DataReader ( Eg: SqlDataReader, etc., )
      • Parameter ( Eg: SqlParameter, etc., )
      • Transaction ( Eg: SqlTransaction, etc., )
    • Each provider use different namespace. Their namespaces are in respective:
      • System.Data.SqlClient
      • System.Data.OleDb
      • System.Data.Odbc
      • System.Data.OracleClient
    • In addition to above namespaces few more important namespaces in ADO.NET are:
      • System.Data
      • System.Data.Common
      • System.Data.SqlTypes
    • ADO.NET consists number of classes that are used regardless you are using the SQL Server classes or OLEDB classes.
    • The System.Data namespace consists the following classes:
    • DataSet DataTable DataRow
    • DataColumn DataRelation Consraint
    • These classes are used by all data providers.
  • Classes in Data Providers
    • Each data provider supports the following types of core objects to communicate with database.
    • The Connection object provides connectivity to a data source.
    • The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information.
    • The DataReader provides a high-performance stream of data from the data source.
    • Finally, the DataAdapter provides the bridge between the DataSet object and the data source.
      • The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.
  • Types of Architecture
    • ADO.NET is both connection oriented as well as disconnection oriented
    • Connected : Forward-only, read-only
      • Application issues query then reads back results and processes them
      • DataReader object
    • Disconnected
      • Application issues query then retrieves and stores results for processing
      • Minimizes time connected to database
      • DataSet object
  • Connection Object
    • The different Connection classes are in different data provider models.
    • Eq: SqlConnection, OleDbConnection, OracleConnection, etc.,
    • The properties of SqlConneciton class are:
      • ConnectionString, DataSource, Database, State
      • In above properties DataSource, Database, State are read only.
    • You can pass necessary connection string information to the to the SqlConnection in a string format or store in web.config file.
      • You can store database connection parameters in configuration file under <connectionString> section. Here you can specify name of connection, connection string parameters and provider for this connection.
    • Example usage of SqlConnection :
    • SqlConnection conn = new SqlConnection(“Server=localhost, database=…,”);
    • conn.Open()
    • //Use connection object.
    • conn.Close(); //You need to call this explicitly. Because .NET doesn’t implicitly // release the connection when they fall out of scope.
    • <configuration>
    • < connectionString >
    • <add name = “ My NWConnection ” providerName =“ System.Data.SqlClient ”
    • connectionString = “server=(local);” +
    • “ User id=ible;password=iblesoft; database=Northwind”;
    • </ connectionString >
    • </configuration>
    • To load the connection string from web.config file.
    • SqlConnection conn = new SqlConnection();
    • conn . ConnectionString = ConfigurationManager.ConnectionStrings [&quot;MyNWConnection&quot;]. ConnectionString ;
  • Command Object
    • In ADO.NET a command is a string of text containing SQL statements that is to be issued to the database. It can also be a stored procedure or the name of table which returns all columns and rows.
      • A command can be constructed by using the instance of SqlCommand .
      • SqlComand cmd = new SqlCommand(“ SELECT * from Customers ”, conn);
      • After building the command object you need to execute with any one of methods:
        • ExecuteNonQuery(): Executes the command but doesn’t return any output. Only it returns no of rows effected.
        • ExecuteReader(): Execute command and returns a type SqlDataReader.
        • ExecuteRow(): Execute the command and returns SqlRecord. ( Single row )
        • ExecuteScalar(): Execute the command and returns a single value.
        • ExecuteXmlReader(): Executes the command and returns XmlReader .
        • All these methods will be issued from Command object.
      • Some of the important properties of Command object are:
        • CommandText: Assign SQL statement or stored procedure name.
        • CommandTimeout: Specifies no of second to wait for executing a command.
        • CommandType: Possible values are Text, Stored Procedure, Table direct.
        • Connection : Gets or Sets SqlConnection object.
    • Calling a stored procedure with a Command object: SqlCommand cmd = new SqlCommand(“ MyStoredProc &quot;, conn);
    • cmd. CommandType = CommandType.StoredProcedure;
    • cmd.Parameters.Add(new SqlParameter( …));
      • cmd.Parameters[ 0 ].Value = val ;
      • cmd.ExecuteNonQuery();
  • Data Reader
    • A data reader ( SqlDataReader , etc.,) is a simple and fastest way of selecting some data from a data source but also least capable.
      • You can’t directly instantiate a data reader object. An instance is returned from appropriate Command object after having call ExecuteReader() method.
      • This data reader is forward-only, read-only connected cursor. You can only travels the records in one direction. Database connection used is kept open until the data reader has been closed.
      • The DataReader object requires a live connection to the database.
        • So When you are done with DataReader object, be sure to call Close() . If not the connection stays alive.
      • When DataReader object is closed (via an explicit call to Close ) or the object being garbage collected, the underlying connection (conn) may also be closed depending on which of the ExecuteReader() method is called.
      • If you call ExecuteReader() and pass CommandBehavior.CloseConnection you can force the connection to be closed when the reader is closed.
  • Data Reader
      • For Data Reader object you have the following methods:
        • Read(): Reads record by record in the data reader.
        • Close(): Closes the SqlDataReader connection
        • Dispose(): Disposes the data reader object.
      • Some of the important properties of Data Reader object are:
        • Connection: Gets the SqlConnection associated with the SqlDataReader .
        • HasRows: Gets the value that indicates whether the SqlDataReader contains one or more rows.
        • IsClosed: Retrieves a Boolean value that indicates whether the specified SqlDataReader instance has been closed.
  • Data Adapter
    • The Data Adapter classes (Eg: SqlDataAdapter , ..) bridges the gap between the disconnected DataTable objects and the physical data source.
    • The SqlDataAdapter provides two way data transfer mechanisms:
      • It is capable of executing SELECT statement on a data source and transferring the result set into a DataTable object.
      • It is also capable of executing the standard INSERT, UPDATE and DELETE statements and extracting the input data from a DataTable object.
    • The commonly used properties of SqlDataAdapter class are:
      • SelectCommand: Gets or sets an object of type SqlCommand . This command is automatically executed to fill a DataTable with the result set.
      • InsertComand: Gets or sets an object of type SqlCommand .
      • UpdateCommand: Gets or sets an object of type SqlCommand .
      • DeleteCommand: Gets or sets an object of type SqlCommand .
    • This SqlDataAdapter class also provide a method called Fill() .
      • Calling the Fill() method automatically execute the command provided by the SelectComand property and retrieve the result set and copies it to DataTable.
  • Using Parameter
    • If you requires SQL Statements that required you to configure using parameters then you need to instantiate Parameter (i.e., SqlParameter ,.., ) object and providing it with necessary information such as name, value, type, size, direction, etc.,
    • The following are properties of the SqlParameter class: ( All are RW)
      • ParameterName, SqlDbType, Size. Direction, SourceColumn, Value
    • Coding Snipped in using parameters are:
    • SqlCommand myCmd = new SqlCommand ();
    • myCmd.CommandText = &quot;SELECT * FROM CUSTOMERS WHERE CITY=@CITY&quot;;
    • SqlParameter parmCity = new SqlParameter ();
    • parmCity. ParameterName = &quot;@CITY&quot;;
    • parmCity. SqlDbType = SqlDbType.VarChar;
    • parmCity. Direction = ParameterDirection.Input;
    • parmCity. Value = “New York” ;
    • myCmd.Parameters.Add(parmCity);
  • DataSet
    • The DataSet class has been designed as an offline container of data.
      • Data held within the DataSet is not necessary to come from database. It can be recorded from CSV file, XML source, etc.,
      • A DataSet class contains a set of DataTable classes and links between tables.
    • Eg: foreach( DataRow row in ds.Tables[“Customers”].Rows)
    • Console.WriteLine(“{0} and {1}”, row[0], row[1]);
      • Each DataTable class consists DataColumn , DataRow, Constraints and ExtendedProperties classes.
      • Here DataColumn object defines the properties of a column within DataTable . These properties includes data type (Int32, Char, DateTime, etc.,), read-only. You can also assign a name for column.
      • DataColumn customerID = new DataColumn(&quot;CustomerID&quot;, typeof(int));
      • customerID.AllowDBNull = false;
      • customerID.ReadOnly = false;
      • customerID.AutoIncrement = true;
      • customerID.Unique = true;
      • The actual data within a table is accessed via a DataRow object. One of the interesting aspect of DataRow is that it is versioned. This permits you to receive various values for a given column in a particular row.
  • DATA SET DataSet DataTable DataRelation DataRow DataColumn
  • DataSet Architecture
    • You can create DataSet in any one of the following methods:
      • Using Server Explorer
      • Using DataAdapter
      • Programmatically
      • Using XML
    Dataset TablesCollection DataTable ColumnsCollection RowsCollection ConstraintsCollection DataColumn DataRow Constraint RelationsCollection DataRelation
    • Coding snippet of using DataSet:
    • SqlConnection conn = new SqlConnection (…);
    • SqlDataAdapter da = new SqlDataAdapter (cmd, conn);
    • DataSet ds = new DataSet ();
    • da.Fill( ds , “MyTable”);
    • Better guideline regarding DataSet is:
      • Don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects.
      • If you are working with single table then just use DataTable object rather then DataSet .
  • DataSet
    • You can create schemas for a DataTable in three ways.
      • Let the runtime do it for you
      • Write code to create the tables(s).
      • Use the XML schema generator.
    • The DataAdapter class is used to place the data in a DataSet class. This adapter class issues the SQL clause and fills a table within the DataSet.
    • SqlDataAdapter da = new SqlDataAdapter(strCmd, conn);
    • DataSet ds = new DataSet();
    • da.Fill(ds, “Customers”); // Populating DataSet with DataAdapter.
    • The DataSet class has been designed to establish relationships between data tables with ease.
    • At present you can apply the ForeignKeyConstraint and UniqueConstraint on a columns in a DataSet.
    • You can also set Update & Delete constraints on a columns that have constraint relationships. These rules are:
      • Cascade, None, SetDefault, SetNull.
    • DataTable dt = GetDataTable(); //It returns DataTable
    • DataColumn[] pk = new DataColumn[1];
    • pk[0] = dt.Columns[“StudentID”];
    • dt. PrimaryKey = pk;
    • The constrains are enforced within a DataSet class if the EnforcedConstraints property of the DataSet is true.
  • ADO.NET Programming
    • ADO.NET programming involves the following steps:
      • Create a Connection object and provide connection string information.
      • Create a Command object and provide details of SQL command that is to be executed.
        • Command can be inline SQL Text command, Stored Procedure or direct table access . Also provide required parameters if needed.
      • If your command doesn’t return result set then execute the command simply by calling one of Execute method on Command object.
      • If your command object returns a result set then you can store the result set in DataReader or DataAdapter object.
      • To load the data from DataReader to DataTable just call Load() method on DataTable .
      • SqlDataReader myReader = cmd.ExecuteReader(..);
      • DataTable myTable = new DataTable();
      • myTable.Load(myReader);
      • In reverse if you want a reader from DataTable then use:
        • DataTableReader myReader= myTable.CreateDataReader();
        • If you want to retain the result set for feature use without maintaining the connection to the database then use DataAdapter object. This DataAdapter object is used to fill DataSet or DataTable objects.
        • If you don’t want to retain the result set, rather simply process the command in a swift fashion, you use Command object to create a DataReader object. The DataReader object needs a live connection to database and it works as forward-only read-only cursor.
  • DataGridView Control
    • The DataGridView control is an enhanced version of old DataGrid control.
    • This new DataGridView control has binding capabilities similar to old controls. It can bind to an Array, DataTable, DataView or DataSet Class or a component that implements IListSource or IList interface.
    • This DataGridView control gives you variety of views of the same data. This control have two important properties:
      • AutoGenerateColumns
      • DataSource
    • The DataGridView control has built in support for image columns, buttons, and combo boxes, etc.,
    • The DataView provides a means to filter and sort data within a DataTable .
        • DataView dv = new DataView(dataTable);
      • After DataView has been created, the data displayed by the view can be altered by setting the RowFilter property based on user clause (Eg: Client = ‘Smith’).
      • A DataView doesn’t permit the filtering of columns, only rows.
    • DataView Filtering:
    • DataSet ds = new DataSet();
    • SqlDataAdapter da = new SqlDataAdapter(strCustomer, conn);
    • da.Fill(ds, &quot;Customers&quot;);
    • DataView dv = new DataView(ds.Tables[&quot;Customers&quot;]);
    • dv.RowFilter = &quot;Country='USA'&quot;;
    • dataGridView1.DataSource = dv; //Displays only USA customers.
  • DataGridView Control
    • The DataGridView control also support to display generic collections. To display collection only need to set DataSource property to collection object .
      • Here the columns displayed are based on properties on collection object. All public readable fields are displayed in the DataGridView.
    • When you specifying the data source to DataGridView control, by default it will construct columns automatically ( i.e., AutoGenerateColumns = true);
      • While constructing if any of the columns data type found as bool then it will create a check box for that column ( i.e, DataGridViewCheckBoxColumn ).
      • Programmatically you can create the following different types of columns all these column are derived from DataGridViewColumn ( Here AutoGeneratedColumn property of DataGridView is set to false. ) .
        • DataGridViewButtonColumn,
        • DataGridViewCheckBoxColumn,
        • DataGridViewComboBoxColumn,
        • DataGridViewImageColumn,
        • DataGridViewLinkColumn,
        • DataGridViewTextBoxColumn.
    • Example code how to add Image Column to DataGridView:
    • DataGridViewImageColumn photoColoumn = new DataGridViewImageColumn ();
    • photoColoumn.DataPropertyName = &quot;Photo&quot;; //Table column name
    • photoColoumn.Width = 100;
    • photoColoumn.HeaderText = &quot;Image&quot;; //Display Column Header
    • photoColoumn.ReadOnly = true;
    • dataGridView1.Columns.Add(photoColoumn);
  • DataGrid Control
    • One of the feature of DataSet is able to define relation ship between tables. This type of relationship can’t display in DataGridView control. But it is possible in DataGrid control
      • Once you populate those tables data to DataSet and established the relationship between them in DataSet. Then you can display these related data by just simply calling DataGrid control function SetDataBinding() method.
      • This feature is not available with DataGridView .
    • Once you clicked that particular CustomerOrders it will automatically displays all the orders displayed for that particular Customer.
    • This is possible in DataGrid control only.
  • Data Binding
    • ASP.NET is capable to bind the collection of data to controls at runtime with no or little code effort.
    • ASP.NET 2.0 a new layer of data abstraction called data source controls . These controls abstract the use of underlying data providers such as SQL Data provider or OLE DB Data Provider.
    • The following five different types of Data Source Controls available in ASP.NET 2.0. All these controls are derived from Control class.
      • SqlDataSource Control
      • ObjectDataSource Control
      • XmlDataSource Control
      • SiteMapDataSource Control
      • AccessDataSource Control
      • LinqDataSource Control
    • One of the interesting property of SqlDataSource control is DataSourceMode property. It tells the control whether it should use DataSet or DataReader internally when retrieving the data.
    • The code generated for SqlDataSource control on your web page is:
    • <asp:SqlDataSource ID =&quot;SqlDataSource1&quot; runat =&quot;server&quot;
    • ConnectionString =&quot;<%$ ConnectionStrings:MyNWConnection %>&quot;
    • DataSourceMode =&quot;Data Set &quot;
    • SelectCommand =&quot;SELECT * FROM [Customers]&quot;>
    • </asp:SqlDataSource>
    • All the data source control works in the similar manner. One important difference when working with Access data source control is that it doesn’t use ConnectionString property it uses DataFile property to specify data source.
  • Data Binding
    • In ASP.NET all the connection related settings are stored in web.config file. This configuration file consists <connectionStrings> section to store all your connections. The .NET exposes this <connectionStrings> section to programs using the ConnectionStringSettings class.
      • In addition to above class you can use SqlConnectionStringBuilder class.
      • SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
      • builder.DataSource = “IBLESOFT&quot;;
      • builder.InitialCatalog = &quot;NorthWind&quot;;
      • builder.UserID = “rajini&quot;; builder.Password = “krajini&quot;;
      • ConfigurationManager.ConnectionStrings[&quot;MyNWConnString&quot;].ConnectionString = builder.ConnectionString;
    • Programmatically creating connection string and adding it to Web.config file.
    • ConnectionStringSettings conn = new ConnectionStringSettings();
    • conn.ConnectionString = &quot;Data Source=IBLESOFT;Initial Catalog=Northwind;Integrated Security=True&quot;;
    • conn.Name = &quot;MyNWConnString&quot;;
    • conn.ProviderName = &quot;System.Data.SqlClient&quot;;
    • //Now add this new connectin string to the web.config. ConfigurationManager.ConnectionStrings.Add(conn);
    • Thank You !