Ch 7 data binding


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Ch 7 data binding

  2. 2. INTRODUCTION TO DATA BINDING Almost every web application has to deal with data,whether it’s stored in a database, an XML file, a structuredfile, or something else. Retrieving this data is only part of the challenge—amodern application also needs a convenient, flexible, andattractive way to display the data in a web page. ASP.NET includes a rich and full-featured model fordata binding. Data binding allows you to bind the data objects you’veretrieved to one or more web controls, which will then showthe data automatically. Don’t need to write time-consuming logic to loop through 2rows, read multiple fields, and manipulate individual
  3. 3. Introduction to Data Binding cont.. Tomake your life even easier, useASP.NET’s data source controls. A data source control allows you todefine a declarative link between yourpage and a data source. Configure a data source control, andhook it up to your web controls at designtime, and ASP.NET will take care of all thedata binding details. 3
  4. 4. Basic Data Binding Data binding is a feature that allows you toassociate a data source with a control and have thatcontrol automatically display your data. Key characteristic is that it’s declarative. Most web controls (including TextBox, LinkButton,Image, and many more) support single-value databinding. To use single-value binding, create data bindingexpressions. Many web controls support repeated-value binding. Assign DataSource property of the control to data 4
  5. 5. Single-Value Binding The controls that support single-value data binding allow you tobind some of their properties to a data bindingexpression. The expression is entered in the .aspx markup portion of thepage, not in code behind file. Here’s an example: <%# expression_goes_here %> For example, if you have variable in your page class namedEmployeeName, you could write the following: <%# EmployeeName %> To evaluate a data binding expression such as this, call thePage.DataBind() method. The following data binding expressions are all valid: <%# GetUserName() %> <%# "John " + "Smith" %> 5
  6. 6. Other Types of Expressions ASP.NET also has support for a different type of expression,commonly known as $ expressions. $ expression is a code sequence in an .aspx page and will beevaluated by an expression builder when the page is rendered. ASP.NET includes a built-in expression builder that allows toextract custom application settings and connection string informationfrom the web.config file. For example, if you want to retrieve an application setting namedappName from the <appSettings> <asp:Literal Runat="server" Text="<%$ AppSettings:appName%>" /> Here’s an example that uses theConnectionStringsExpressionBuilder:<asp:Literal Runat="server" Text="<%$ ConnectionStrings:Northwind 6
  7. 7. Repeated-Value Binding Repeated-value binding allows you to bind anentire list of information to a control. Could be a collection of custom objects (forexample, in an ordinary ArrayList or Hashtable) or acollection of rows (for example, with a DataReader orDataSet). Important properties of repeated controls:  DataSource  DataSourceID  DataTextField 7  DataTextFormatString
  8. 8. Binding to a DataReader Can bind any data structure that implements theICollection interface or one of its derivatives.The following list summarizes many of these dataclasses  All in-memory collection classes, such as Collection, ArrayList, Hashtable, and Dictionary.  An ADO.NET DataReader object, which provides connection-based, forward-only, and read-only access to the database  The ADO.NET DataView, which provides a view onto a single disconnected DataTable object.  Any other custom object that implements the 8
  9. 9. The Rich Data Controls In addition to the simple list controls, ASP.NETincludes some rich data controls that support repeated-value binding. Rich Controls are designed exclusively for databinding. Support higher-level features such as editing and otherfeatures. The rich data controls include the following:  GridView : The GridView is an all-purpose grid control for showing large tables of information  DetailsView: Shows a single record at a time, in a table that has one row per field 9  FormView: FormView shows a single record at a
  10. 10. The Rich Data Controls cont.. GridView provides a DataSource property for the dataobject. DataBind() method triggers to read the data object anddisplay each record. GridView automatically generates a column for everyproperty or every field. For Example: <asp:GridView ID="grid" runat="server" AutoGenerateColumns="true" /> Now, define a query that selects several fields from the Employees string sql = "SELECT EmployeeID, FirstName,LastName, Title, City " + "FROM Employees"; Bind the GridView to a DataReader . 10 grid.DataSource = reader;
  11. 11. Data Source Controls To access database data access code is needed.With data source controls, you can avoid writing any dataaccess code. The data source controls include any control thatimplements the IDataSource interface. The .NET Framework includes the following data sourcecontrols: Data Source Control Description SqlDataSource Allows you to connect to any data source that has an ADO.NET data provider. Includes SQL Server, Oracle, and the OLE DB or ODBC data sources. ObjectDataSource Allows you to connect to a custom data access class. AccessDataSource Allows you to read and write the data in an Access database file (.mdb). XmlDataSource allows you to connect to an XML file SiteMapDataSource allows you to connect to the Web.sitemap file that 11 describes the navigational structure of your website
  12. 12. The SqlDataSource Data source controls turn up in the .aspx markupportion of your web page like ordinary controls. Here’s an example: <asp:SqlDataSource ID="SqlDataSource1"runat="server" ... /> The SqlDataSource represents a databaseconnection that uses an ADO.NET provider..NET ships with these four provider factories  System.Data.SqlClient  System.Data.OracleClient  System.Data.OleDb  System.Data.Odbc 12
  13. 13. The SqlDataSource cont.. The next step is to supply the required connection string. For example <configuration> <connectionStrings> <add name="Northwind“ connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI"/> </connectionStrings> ... </configuration> Specify it in the SqlDataSource using a $ expression. <asp:SqlDataSource ConnectionString= "<%$ ConnectionStrings:Northwind %>" ... /> 13
  14. 14. Selecting Records Each SqlDataSource control allows you to retrieve a singlequery. Can add corresponding commands for deleting, inserting, andupdating rows. The SqlDataSource command logic is supplied through fourproperties:  SelectCommand,  InsertCommand,  UpdateCommand, and  DeleteCommand Example: <asp:SqlDataSource ID="sourceEmployees" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind 14%>" SelectCommand="SELECT EmployeeID, FirstName,
  15. 15. Selecting Records cont.. Clearly, the great advantage of the data sourcecontrols is that they allow you to configure data bindingat design time, without writing tedious code. Controls can be bound to a DataReader or aDataView Which approach does the SqlDataSource controluse?  DataSourceMode to SqlDataSourceMode.DataSet (the default) or to SqlDataSourceMode.DataReader. The DataSet mode is almost always better, becauseit supports advanced sorting, filtering, and caching 15
  16. 16. Parameterized Commands Can we pass parameters to SqlDataSourceMode??? <asp:SqlDataSource ID="sourceEmployees"runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ConnectionStrings:Northwind %>" SelectCommand="SELECT EmployeeID, FirstName, LastName,Title, City FROM Employees WHERE City=@City"> <SelectParameters> <asp:ControlParameter ControlID="lstCities"Name="City" PropertyName="SelectedValue" /> 16 </SelectParameters>
  17. 17. Stored ProceduresCan we use stored procedure with SqlDataSourcecontrol???<asp:SqlDataSource ID="sourceEmployees"runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ConnectionStrings:Northwind %>" SelectCommand="GetEmployeesByCity" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:ControlParameter ControlID="lstCities"Name="City" PropertyName="SelectedValue" /> 17 </SelectParameters>
  18. 18. More Parameter Types Parameter values aren’t necessarily drawn from othercontrols. Can map a parameter to any of the parameter types definedin table below Control Tag Source Description Control property <asp:ControlParameter> A property from another control on the page. Query string <asp:QueryStringParamete A value from the current query value r> string. Session state <asp:SessionParameter> A value stored in the current user’s value session. Cookie value <asp:CookieParameter> A value from any cookie attached to the current request. Profile value <asp:ProfileParameter> A value from the current user’s profile A form variable <asp:FormParameter> A value posted to the page from an input control. 18
  19. 19. More Parameter Types cont.. Don’t need to remember the different tag names Visual Studio provides a handy editor that lets youcreate your command and define your parameters. 19
  20. 20. Updating Records  ASP.NET’s rich data controls—including the GridView, DetailsView, and FormView—all have editing features  First step is to define suitable commands for the operations (like InsertCommand, DeleteCommand, and UpdateCommand)  Example <asp:SqlDataSource ID="sourceEmployees" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind %>" SelectCommand="SELECT EmployeeID, FirstName, LastName, Title, City FROM Employees" UpdateCommand="UPDATE Employees SET FirstName=@FirstName, LastName=@LastName,Title=@Title, City=@City FROM Employees WHERE EmployeeID=@EmployeeID">To enable editing, set the GridView.AutoGenerateEditButton property 20to true.
  21. 21. Updating Records Can use stored procedures to update the records Example <asp:SqlDataSource ID="sourceEmployees" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind%>" SelectCommand="SELECT EmployeeID, FirstName,LastName, TitleOfCourtesy FROM Employees" UpdateCommand="UpdateEmployee" UpdateCommandType="StoredProcedure" OnUpdating="sourceEmployees_Updating" > <UpdateParameters> <asp:Parameter Name="First" Type="String"/> <asp:Parameter Name="Last" Type="String"/> 21 </UpdateParameters>
  22. 22. Deleting Records Deletinga record is similar to updating it. Create a DeleteCommand that removes the recordyou want to delete. Example<asp:SqlDataSource ID="sourceEmployees"runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ConnectionStrings:Northwind %>" SelectCommand="SELECT EmployeeID,FirstName, LastName, Title, City FROMEmployees" 22 DeleteCommand="DELETE Employees
  23. 23. Inserting Records The GridView supports editing and deleting records, but itdoesn’t support insertion. However, the DetailsView and FormView do supportinsertion. Example<asp:SqlDataSource ID="sourceEmployees" runat="server" ProviderName="System.Data.SqlClient" ConnectionString="<%$ ConnectionStrings:Northwind%>" SelectCommand= "SELECT EmployeeID, FirstName, LastName, Title,City FROM Employees” InsertCommand="INSERT INTO Employees (FirstName,LastName,Title,City) VALUES (@FirstName,@LastName,@Title,@City)"> 23
  24. 24. Disadvantages of the SqlDataSource Data access logic embedded in the page. Maintenance in large applications. Lack of flexibility. Inapplicability to other data tasks. 24