| Data Binding in ASP.Net 2.0 |
| |
| Steps to Add Data Source Control in Web Page |
| |
| Before describing about the Web Server Control here you should know the procedure to use in a practical way. It will make easy for you to use it by reading out these steps. |
| |
| The procedure to use any server control in Web Page is given below: |
| |
Step 1. Open Visual Studio 2005, click on âFile? Menu and select âWeb Siteâ¦? in the âNew? sub menu then you will get âNew Web Site? dialog box.
Step 2. In âNew Web Site? dialog box, select language and press âOK? then a default.aspx web page will be opened which is available in source view mode.
Step 3. Select âDesigner? from View Menu (press Shift+F7) to see the default.aspx web page in design view.
Step 4. Select the item âData? in the toolbox tab (press Cltr+Alt+X if not visible) from left hand side in Visual Studio.
Step 5. Select the Data Source Control in the toolbox.
Step 6. Keeping mouse button pressed, dragged it to the web form.
Step 7. To configure the Data source control with data source select it and either select âConfigure Data Source? from the smart tag of control or you can configure Data Source control by using properties in Properties Window.
The Data source control configuration requires many steps and common steps for all Data source controls is given below:
1. Select the âConfigure Data Source? from the smart tag of control then Configure Data Source dialog box will be opened.
2. In Configure Data Source dialog box, select data base or data base file (like myaccessdatabase.mdb or myxmldatabase.xml).
3. You can edit the fields by selecting âEdit Fieldsâ¦? option present in the smart of Data Binding control like Grid view.
Step 8. You can set properties of the Data Source control from the Properties Window. |
| |
| Remember that the Data Source Control will not be visible at run time and after dragging on the web page, its look in design view mode is given in as figure below: |
| |
 |
| |
| ObjectDataSource Control |
| |
| This control is designed to interact with an object that implements one or more methods to get back or modify data. The ObjectDataSource control works with a business object or other class in Web applications that depend on middle-tier business objects to manage data. |
| |
| The ObjectDataSource control acts as a data interface for data-bound controls like GridView, FormView, or DetailsView controls, and enable those controls to display and edit data from a middle-tier business object on an ASP.NET Web page. |
| |
| If the data is returned as a DataSet, DataTable, or DataView object, the ObjectDataSource control can cache and filter the data. You can also implement advanced paging setting if the source object accepts page size and record index information from the ObjectDataSource control. |
| |
| Retrieving and Updating Data |
| |
| The ObjectDataSource control supports three-tier architecture by providing a way for you to bind data controls on the page to a middle-tier business object. The ObjectDataSource works with a middle-tier business object to select, insert, update, delete, page, sort, cache, and filter data declaratively without extensive code. |
| |
| ObjectDataSource control uses Reflection to expose and call the appropriate methods of a business object to select, insert and update data. You set the TypeName property of the ObjectDataSource control to specify the name of the class to use as a source object. Using SelectMethod property, you can get or set the name of the method or function that the ObjectDataSource control invokes to get data. |
| |
| Data Sorting and Paging |
| |
| The ObjectDataSource control has additional sorting and paging capabilities by passing sort and page information in requests from a data-bound control, such as a GridView control, to the data object for processing. The source data object or the data source control itself can then sort data and return data in pages. Using SortParamerterName property, you can get or set the name of the business object that the SelectMethod parameter uses to specify a sort expression for the data source sorting support. |
| |
| Data Caching |
| |
| The ObjectDataSource control can cache objects returned by the underlying business object. Enable Caching property get or sets a value indicating whether the ObjectDataSource control has data caching enabled. However, you should not cache objects that hold resources or that maintain state that cannot be shared among multiple requests, such as an open DataReader object. |
| |
| Data Filtering |
| |
| If the object returned to the ObjectDataSource control by the source data object is a DataSet or DataTable object, the ObjectDataSource control supports filtering using the syntax of the FilterExpression property of the DataColumn class. Filtering allow you to expose only rows that match particular search criteria, without having to re-query the data source with new selection criteria. |
| |
| Detection of Conflict Data |
| |
| Set the ConflictDetection property of ObjectDataSource control to true as it get or set a value that just determines whether or not the new values are passed to the update method or both old and new values are passed to the Update Method. The original values can then be included in checks for optimistic concurrency. |
| |
| SqlDataSource Control |
| |
| You can access and manipulate data in an ASP.NET page without using ADO.NET classes directly by using a SqlDataSource control. The SqlDataSource control represents a connection to an ADO.NET SQL database provider, such as SQL, OLEDB, ODBC, or Oracle. The SqlDataSource control enables you to use a Web control to access data placed in a relational data base. Similar to all data source controls, the SqlDataSource control can be declaratively bound to any data-bound control that supports the DataSourceID property. At run time, the SqlDataSource control automatically opens the database connection, executes the SQL statement or stored procedure, returns the selected data (if any), and then closes the connection. |
| |
| The SqlDataSource control utilizes ADO.NET classes to interact with any database supported by ADO.NET. This includes Microsoft SQL Server (using the System.Data.SqlClient provider), System.Data.OleDb, System.Data.Odbc, and Oracle (using the System.Data.OracleClient provider). |
| |
| It is important to note that a separate AccessDataSource control is implemented in ASP.NET, although it is possible to connect to Access with SqlDataSource as well (using the Microsoft Jet 4.0 OLEDB provider) |
| |
| Connection between the SqlDataSource Control and a Data Source |
| |
| When you configure a SqlDataSource control, you set the ProviderName property to the type of database (the default is System.Data.SqlClient) and the ConnectionString property to a connection string that contains information required to connect to the database. |
| |
| Instead of setting connection strings at design time as property settings in the SqlDataSource control, you can store them centrally as part of your application's configuration settings using the connectionStrings configuration element. In this way you can manage connection strings independently of your ASP.NET code, including encrypting them using Protected Configuration. The following example shows a connection to the SQL Server Northwind sample database using a connection string stored in the
configuration element named MyNorthwind. |
| |
<%@ Page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommand="SELECT LastName FROM Employees">
</asp:SqlDataSource>
<asp:ListBox
id="ListBox1"
runat="server"
DataTextField="LastName"
DataSourceID="SqlDataSource1">
</asp:ListBox>
</form>
</body>
</html> |
| |
| Executing Data Commands with the SqlDataSource Control |
| |
| You can use up to four commands (SQL queries) for the SqlDataSource command: a SelectCommand, UpdateCommand, DeleteCommand, and an InsertCommand. For every command property, you specify a SQL statement for the data source control to execute. If the data source control connects to a database that supports stored procedures, you can specify the name of a stored procedure in place of the SQL statement. Specify the name of a stored procedure in place of the SQL statement for executing stored procedures. |
| |
| You can also generate parameterized commands that include placeholders for values to be supplied at run time as given below : |
| |
| Select CustomerID, CompanyName From Customers Where City = @city |
| |
| The Select method is called automatically on calling the DataBind method of the page or of a control bound to the data source control. You can also call any of the four methods explicitly when you want the data source control to execute a command. |
| |
| Returning DataSet or DataReader Objects |
| |
| You can set the data source control's DataSourceMode property type to return data. The SqlDataSource control can return data in two forms: as a DataSet object or as an ADO.NET data reader. You can choose to return a dataset to filter, sort, or page through data after retrieving it or to maintain a cache. In contrast, you can use a data reader to return the data and are using a control on the page to display that data |
| |
| Caching the SqlDataSource Control |
| |
| The SqlDataSource control can cache the retrieved data, which can enhance the performance of the applications by avoiding expensive queries. You can permit caching by setting EnableCaching to true. You can set the CacheDuration property to the number of seconds to cache data. The data source control maintains a separate cache entry for each combination of connection, select command, select parameters, and cache settings. |
| |
| The SqlDataSource control can also take advantage of the cache dependency feature of SQL Server (if available in your version of SQL Server). This feature allows you to specify that the data in the cache is maintained until SQL Server reports a change in the specified table. This type of caching allows you to improve the performance of data access in your Web applications, because you can minimize data retrieval to only those times when it is necessary to get refreshed data. |
| |
| Filtering the SqlDataSource Control |
| |
| You can also filter the data without re-running the query even for a SqlDataSource control with enabled caching. The SqlDataSource control uses a FilterExpression property that allows you to specify selection criteria that are applied to the data maintained by the data source control. You can also parameterize the filter expression by creating special FilterParameters objects that provide values at run time to the filter expression. |
| |
| Sorting the SqlDataSource Control |
| |
| The SqlDataSource control helps to sort requests from the bound control when the DataSourceMode is set to DataSet. |
| |
| AccessDataSource Control |
| |
| The AccessDataSource control is a data source control that maintains a connection to a Microsoft Access database (.mdb file) and makes the database data available to other controls on an ASP.NET Web page. The AccessDataSource control is a specific case of the SqlDataSource control, planned to work particularly with Microsoft Access .mdb files. As with the SqlDataSource control, you use SQL statements to define how the control fetches and retrieves data. |
| |
| The AccessDataSource control inherits the SqlDataSource class and uses the DataFile property in place of the ConnectionString property to make it convenient to connect to a Microsoft Access database. |
| |
| The AccessDataSource control sets the ProviderName property of the base SqlDataSource class to the System.Data.OleDb provider and connects using the Microsoft.Jet.OLEDB.4.0 OLE DB provider. You cannot set the ProviderName or ConnectionString properties of the AccessDataSource control. |
| |
| It is important to notice that to retrieve data from a password-protected Access database, use the SqlDataSource control, otherwise you are not able to maintain a connection. |
| |
| Selecting Data Using the AccessDataSource Control |
| |
| You can set an SQL query for the AccessDataSource control to execute by setting its SelectCommand property as given in the following code sample. |
| |
<form id="form1" runat="server">
<asp:AccessDataSource
id="EmployeesDataSource"
DataFile="~/App_Data/Northwind.mdb"
runat="server"
SelectCommand="SELECT EmployeeID, FirstName, LastName FROM Employees" />
<asp:GridView
id="EmployeesGridView"
runat="server"
AutoGenerateColumns="True"
DataSourceid="EmployeesDataSource" /> |
| |
| Similarly you can get results from a Microsoft Access query by setting the StoredProcedure in place of SelectCommand in SelectCommandType property. |
| |
| Passing Parameters |
| |
| You can supply parameters at run time by executing parameterized queries for commands. In addition to this, you can specify parameters at run time when calling a Microsoft Access query. (To call a Microsoft Access query, you set the command type property for the command to StoredProcedure |
| |
| As the AccessDataSource control extends the SqlDataSource class and uses the System.Data.OleDb provider, you place parameter placeholders using the "?" placeholder character. The System.Data.OleDb provider does not support named parameters; instead, the parameter values are applied in the order they are specified in the parameters collection. |
| |
| XmlDataSource Control |
| |
| By using XmlDataSource control you can display both hierarchical and tabular data, although the XmlDataSource control is typically used to display hierarchical XML data in read-only mode. |
| |
| The XmlDataSource control reads and writes XML data so that you can work with it using controls such as the TreeView and Menu controls. The XmlDataSource control can read either an XML file or string of XML. If the control is working with an XML file, it can write modified XML back to the source file. If a schema is available that describes the data, the XmlDataSource control can use the schema to expose data using typed members. |
| |
| Displaying XML Data Using the XmlDataSource Control |
| |
| XmlDataSource uses a DataFile property for specifying the path to an XML data file to be used as input. |
| |
| Example: |
| |
<%@ Page Language="C#" Theme="Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>TreeView Bound to XML Data File</title>0
</head>
<body>
<div>
<h2>TreeView Bound to XML Data
<form action="treeviewxmlcs.aspx" runat="server">
<asp:XmlDataSource ID="MyXmlSourceFile"
DataFile="~/App_Data/Bookstore.xml" runat="server"/>
<asp:TreeView ID="MyTreeView"
SkinId="Bookstore"
DataSourceId=" MyXmlSourceFile "
ExpandDepth="3"
MaxDataBindDepth="3"
runat="server" />
</form>
</div>
</body>
</html> |
| |
| Editing XML Data Using the XmlDataSource Control |
| |
| You can use the XmlDataSource to edit XML data. To edit the XML data, call the GetXmlDocument method to get an XmlDocument object, which is an in-memory illustration of the XML data. You can then use the object model exposed by the XmlDocument object and its XmlNode objects, or you can use an XPath expression to manipulate data in the document. Making changes to the in-memory representation of the XML data and then save the data to disk by calling the Save method. This will overwrites the XML file on disk. |
| |
| There are some restrictions on editing XML data using the XmlDataSource control which is given below: |
| |
1. The XML data must be loaded from an XML file specified with the DataFile property, and not from a string of XML specified in the Data property.
2. No XSLT transformation can be specified in the Transform or TransformFile properties.
3. The Save method does not handle concurrent save operations by different requests. It is also possible for a Save operation to fail because of another user is writing to the XML file and has an exclusive lock on the file. |
| |
| XML Data Transformation Using the XmlDataSource Control |
| |
| You can apply an XSLT transformation to the XML data, which allows you to restructure the raw data from the XML file into a format better suited to the control you want to bind to the XML data. |
| |
| If you want to transform the XML data before it is displayed by a data-bound control, As with XML data, you typically load the style sheet from a file, which you specify using the TransformFile property. However, you can also load the style sheet directly from a string using the Transform property. You can set the TransformArgumentList property to provide dynamic XSLT style sheet arguments that is used by the XSL style sheet during the transformation. |
| |
| XML Data Filtration using the XmlDataSource Control |
| |
| You can also apply XPath expressions to the XML data, which allows you to filter the XML data to return only certain nodes in the XML tree, to look for nodes that have specific values in them, and so on. Using an XPath expression disables the ability to insert new data. |
| |
| XML Data Caching using the XmlDataSource Control |
| |
| Caching reduces the processing load on your server at the expense of memory on the Web server; in most cases this is an acceptable trade-off. The XmlDataSource control caches data when the EnableCaching property is set to true, which is the default. You set the CacheDuration property to the number of seconds that the control should cache data. You can use the CacheExpirationPolicy to work smoothly with the caching behavior of the XmlDataSource control. |
| |
| Important to note that if caching is enabled, cached XML data for a single user can be viewed by all users and sensitive information could be visible to an unwanted source. Therefore, it is suggested that set the EnableCaching property to false when client impersonation is enabled and the source file for the XmlDataSource control is retrieved based on the client identityClient impersonation is enabled when the impersonate attribute of the identity configuration element is set to true and anonymous identification is disabled for the application at the Web server. |
| |
| SiteMapDataSource Control |
| |
| The SiteMapDataSource control is used to designing consistent navigation scheme for web application. You can have only one sitemap per site. By default the SiteMapDataSource control will use the default Site Navigation Provider, which is XML-based. Using the Site Navigation API provided in ASP.NET v2.0, you can write your own Site Navigation Provider and expose the navigation information from any back-end system, if needed. |
| |
| The SiteMapDataSource control works with ASP.NET site maps and provides site navigation data. This data includes information about the pages in your Web site, such as the URL, title, description, and location in the navigation hierarchy. Storing your navigation data in one place makes it easier to add and remove items in the navigational menus of your Web site. |
| |
| The SiteMapDataSource is specialized for navigation data and does not support common database operations like sorting, filtering, paging and caching. |
| |
| Setting the default Site Navigation Provider for SiteMapDataSource control |
| |
| Before you add the SiteMapDataSource control to your page, you need to add the Site Navigation Provider. |
| |
| Right Click the solution explorer and click Add New Item. In the templates dialog choose Site Map. |
| |
| Each siteMapNode has three attributes: |
| |
⢠URL: the URL of the page.
⢠Title: the string that will appear in the navigational control.
⢠Description: a short text that will appear as a tooltip if the navigational control supports this feature. |
| |
| Below is an example of a site map file: |
| |
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="www.nodes.com" title="Nodes" description="NodeSample">
<siteMapNode url="www.a_node.com" title="Node A" description="MyNode A" />
<siteMapNode url="www.b_node.com" title="Node B" description="MyNode B" />
</siteMapNode>
</siteMap> |
| |
| Setting the SiteMapDataSource control |
| |
| After you have successfully set the Site Navigation Provider, you can set the SiteMapDataSource control to use it. Point to a navigation control on your site (e.g. TreeView, menu, etc.) and expand the Smart Tag panel of that control. |
| |
| Configure the data source for the control by selecting show Smart Tag option. Open the Choose Data Source dropdown and select the
<New data source...> option. Then choose the SiteMapDataSource control. |
| |
| Setting Data Source Control Caching |
| |
| All data source controls except the SiteMap control enable you to create basic caching polices which includes the cache expiration polices, direction, key dependencies. You can set the cache duration to a specific period of time, like 1800 seconds (30 minutes). You can also set cache duration to infinite to force the cahed data never to expire. |
| |
| Example: |
| |
<asp: SqlDataSource id =?MySqlDataSource?
runat=?server?
SelectCommand=?select query string?
ConnectioString=?connection stirng?
DataSourceMode=?DataSet?
ConflictDetection=?CompareAllValues?
EnableCaching=?True? CacheKeyDependency=?SomeKey? CacheDuration=?Infinite or Time Period?>
<SelectParameters>
<asp:QueryStringParameter Name =?Column Name? QueryStringField= âId?
Type=?String?>
</asp:QueryStringParameter>
</SelectParameters>
<asp:SqlDataSource> |
| |
|
| |