Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data-Aware Controls in ASP.NET ® Applications ASP.NET.

Similar presentations


Presentation on theme: "Data-Aware Controls in ASP.NET ® Applications ASP.NET."— Presentation transcript:

1 Data-Aware Controls in ASP.NET ® Applications ASP.NET

2 Data Binding Techniques A data source represents data – A simple hash table, an array, or a database (or any other collection) – Web controls are used to display the data – Sometimes called Data controls because their primary function is to display data – Displayed in a simple list, drop-down list, or table Data binding is the process of assigning a data source to a Web control – Data can be bound to a variety of Web controls

3 Data Binding Techniques

4 SingleBind.aspx

5 Single-Expression Binding (Page 1) Binds a single value or expression to a control/tag Enclosed within inline server tags, i.e. ( ) Pound/digit symbol (#) before the expression name – Expression is a call to some named procedure, either programmer-defined or built-it (i.e. method or function) – The return value is inserted into the control Example: " runat="server" />

6 Single-Expression Binding (Page 2) The server tag and expression may be entered into for many property lines in the Properties window for Web Server controls (not HTML controls) When the (DataBindings) property is selected, the "DataBindings" dialog window is displayed – Enter the server tag expression into the Custom Binding Expression: window which names the command to execute The radio button must be selected to enter an expression Call DataBind () method usually from Page_Load event to bind the expression to each object

7 Assign Property Value Directly

8 Assign as a Data Binding

9 Key Entry into HTML View

10 Repeated-Expression Binding (Page 1) Repeated expressions are bound to data controls (controls that have a DataSource property) – Could be a collection such as a HashTable, or an ArrayList (i.e. Chapter 4) – DataSet, DataTable, DataView, or DataReader from a database also are repeated expressions CheckBoxList, RadioButtonList, DropDownList and ListBox inherit from ListControls class and may have data from any of the datasources above bound to them

11 Repeated-Expression Binding (Page 2) Data sources also may to bound to the DataGrid and DataList controls which are data controls that inherit from class BaseDataList Repeater inherits from System.Web.UI.Controls class directly

12 Repeated-Expression Binding

13 ASP.NET Data Objects DataSet – A cached (off-line) set of records from a database – Contains one or more DataTables DataTable and DataView – Subset of rows of data from a DataSet DataReader – Read-only, forward-only on-line stream of data from a database

14 Data Binding Web Controls DropDownList—displays one value at a time using the tag; drops-down to display values ListBox—displays values in a box several lines at a time using tag RadioButtonList and CheckBoxList—groups multiple controls Repeater—small, lightweight control that displays data; repeats defined HTML content DataList—displays data from each data row in a list DataGrid—repeats content once for each data row; places the data in a table of rows and columns

15 The DataSource Property For data-aware controls, names the set of data to be displayed by the control Format: controlName.DataSource = arrayList/hashTable/DataSet/DataView Example: ddProducts.DataSource = arrayList1 If a HashTable is assigned to DataSource property: – "Key" is the first element from the hash table – "Value" is the second element from the hash table

16 The DataBind Method Binds one or more data-aware controls so that data is linked to and displayed in the control Format: Page/controlName.DataBind – The Page object may be used to bind all objects when there are more than one on the Web Form Examples: ddProducts.DataBind() Page.DataBind() DataBind()

17 DropDownList.aspx

18 The DataTextFormatString Property (Page 1) Provides formatting for elements in DataBound controls Format string is in two parts, separated by a colon: {"A:Bxx"} – A specifies the index in a zero-based list of parameters (always 0 because there is only one value per element) – B specifies the format to display (C is currency, D is decimal, F is fixed, etc.) – xx specifies the number of decimal places to display

19 The DataTextFormatString Property (Page 2) Example: – {0:F2} – Formats element to display a fixed point number with two decimal places – Advisable to always specify decimal positions to make it easier for other programmers to read your code

20 Other Properties of Bound Controls DataTextField property—text displayed between or associated with the tag block or element DataValueField property—used by the control as the value attribute

21 Binding Data to DropDownList Control Creates an HTML … block with tags Sets the size attribute (height of the object) in the HTML code sent to the browser as equal to 1 – The value 1 is the default for a dropdown list and will not actually be specified in the HTML Example:

22 ListBox.aspx

23 Binding Data to a ListBox Control Creates an HTML … block with tags Sets the size attribute (height of the object) in the HTML code sent to browser to a value greater than 1 Example:

24 CheckBoxRadio.aspx

25 Binding Data to the CheckBoxList and RadioButtonList Controls RadioButtonList and CheckBoxList also are data- aware controls – Each item in series (of CheckBoxes or RadioButtons) is created is an HTML tag with the type attribute equal either "checkbox" or "radio" Example:

26 Binding to a DataGrid Control Creates a grid of rows and columns to display two- dimensional data arrays, i.e. – It might display separate key and value items of a hash table in two columns, each element in its own row – Ideal for displaying records and fields from a database table, view or stored procedure Once the data set exists, set the DataSource property of the DataGrid and call the DataBind () method Example:

27 DataGridSimple.aspx

28 The AutoGenerateColumns Property of the DataGrid Control Specifies whether of not columns in the grid are automatically created from the DataSource when the page loads – By default all columns are displayed in a DataGrid since the AutoGenerateColumns properties is set to True – If set to False, the … block must be used with tags to name fields to display from DataSource Required when using a HashTable since DataGrid does not have DataTextField and DataValueField properties

29 The Control When configuring a data source (i.e. HashTable, DataSet, DataView) programmatically, the DataGrid columns are not created until the code executes The … control block can be added manually to the HTML view to build columns Format: columnElements

30 The Control (Page 1) Displays only selected items from data source in the columns of a DataGrid or other object One or more controls are embedded in the … block Properties: – DataField—names field for display from data source – HeaderText—text displayed at top of column – DataFormatString—uses the same format syntax as the DataTextFormatString

31 The Control (Page 2) Example: <asp:BoundColumn DataField="Value" HeaderText="Price" DataFormatString="{0:C}"> <asp:BoundColumn …

32 Setting DataGrid Formatting Found in the Properties window, separate formatting is available for: – HeaderStyle – ItemStyle – FooterStyle Also may be keyed manually in the HTML view – Be careful to not enter the tag inside a … block Such an error would cause the style of just that one column to be formatted

33 Binding to a DataList Control Used to create a simple, one-dimensional list An control is required in DataList to identify the columns to display and to format data – Like a loop that formats every line in the DataList or other object – Templates are used to store data binding instructions Example: ItemTemplateInformation

34 DataList.aspx

35 Templates (Page 1) Templates – Binds data to individual areas within the control providing the ability to format the control – Combines content, HTML, styles, return values of methods and formatting elements into a single column May be used in a DataGrid to create an HTML stream of characters An ItemTemplate is required for the DataList and Repeater controls – Information will be displayed one time for each row/element in the DataSource, like a loop)

36 Templates (Page 2) Types: – HeaderTemplate—modifies content and appearance of data in header section (first row) – ItemTemplate—configures data rows; and many other HTML elements may be included as well as data source items – FooterTemplate—configures data in footer section (last row) – SeparatorTemplate—configures elements that appear between each of the items – EditItemTemplate—modifies configuration of columns or rows that currently are being edited

37 Templates (Page 3) Example: :

38 The Container.DataItem Function A server expression used in a template to identify the columns to bind to a control Retrieves and stores values, and places them into the HTML output stream Format: Container.DataItem("fieldNameString") Examples: – In the second example, the key (first) element from a hash table is the bound data item

39 The DataBinder.Eval Function A server expression used in a template that, in a single statement, identifies the columns to bind to control along with the formatting instructions Like Container.DataItem function, retrieves values and places them into the HTML output stream Format for data-aware controls: DataBinder.Eval(Container.DataItem, "fieldName", "dataFormatString") Example:

40 Binding Data to a Repeater Control (Page 1) Used to create tables, comma-delimited lists, bulleted lists, and numbered lists Has no default appearance so it must be configured in HTML view Data can be inserted with: – An HTML tag – ASP.NET templates include header, footer, alternating, item and separator templates To position a Repeater control, use the HTML tag or an ASP.NET Panel control

41 Repeater.aspx

42 Binding Data to a Repeater Control (Page 2) Example: ItemTemplateInformation

43 The ADO Objects There are five (5) objects that must be declared: 1. Connection (OleDbConnection) 2. DataAdaptor (OleDbDataAdaptor) 3. Command (OleDbCommand) 4. DataSet 5. DataTable or DataView

44 A programmer-defined identifier which defines the connection to a database file Stores connection information (ConnectionString property) including the DBMS type, as well as the path and filename of database Format: Dim objectName As New OleDbConnection Example: Dim conTaraStore As New OleDbConnection – Prefix for OleDbConnection objects is "con" The OleDbConnection Object

45 A programmer-defined identifier (in this case a reference variable/object) Performs the operations required to communicate between an ASP.NET application and a database file Format: Dim objectName As New OleDbDataAdaptor Example: Dim daProducts As New OleDbDataAdaptor – Prefix for OleDbDataAdaptor objects is "da" The OleDbDataAdaptor Object

46 The OleDbCommand Object A programmer-defined identifier which stores the SQL command information that must execute to establish the database connectivity Stores a command (CommandText property) that may returns specific records – Or store commands to insert, update or delete rows Format: Dim objectName As New OleDbCommand Example: Dim cmdProducts As New OleDbCommand – Prefix for OleDbCommand objects is "cmd"

47 The DataSet Object Programmer-defined identifier (reference variable) which stores the collection of tables … – The object may store more than one table returned by the OleDbDataAdaptor object Tables literally are stored off-line in RAM Format: Dim/Private objectName As New DataSet Example: Dim dsProducts As New DataSet – Prefix for DataSet objects is "ds"

48 Programmer-defined identifier which stores a reference to a single table from a DataSet that is stored in RAM The data then is manipulated off-line – The physical database on disk may be updated after the processing of the data is completed The DataTable object points to one of the tables from the DataSet object The DataTable Object (Page 1)

49 The DataTable Object (Page 2) Format: Dim/Private objectName As DataTable Example : Dim dtProducts As DataTable – The reserved word New is not used because the object variable is a pointer (points to an address in RAM) – Prefix for DataTable objects is "dt"

50 Importing a Namespace (Page 1) Use of the keyword Imports lets developer reference a namespace element from the.NET framework without fully qualifying the element Statement must appear at the top of a module before the class header ("Public Class … ") usually after the Option Explicit and Option Strict statements

51 Importing a Namespace (Page 2) Format: Imports Namespace.Namespace.etc. If "OleDbConnection" class is in System.Data.OleDb namespace the following Imports statement lets the class be called directly: Imports System.Data.OleDb … Dim conTaraStore As New OleDbConnection Instead of: Dim conTaraStore as New System.Data.OleDb.OleDbConnection

52 Linking the Objects (Page 1) There are six (6) steps necessary to create the links between the objects and access the database: 1. Assign a string to the ConnectionString property of the OleDbConnection object: 2.Assign a SQL string to the CommandText property of the OleDbCommand object 3. Assign the Connection object as the Connection property of the Command object 4. Assign Command object as the SelectCommand property of the DataAdaptor object

53 Linking the Objects (Page 2) The six (6) steps necessary to create links between the objects and access the database (con.): 5. Call the Fill method of the DataAdaptor object with the DataSet object as its argument 6. Assign the Tables property of the DataSet object to the DataTable object with the first returned table

54 The ConnectionString Property (Page 1) For the OleDbConnection object, builds a String which establishes the filename and other connection arguments to the data source The information items is in the form of key=value pairs each separated by a semicolon (;) The Provider string specifies the DBMS type, i.e. "Provider=Microsoft.Jet.OLEDB.4.0" The Source string specifies path (location) to the database and its filename, i.e. "Data Source=c:\TaraStore.mdb"

55 Format: ConnectionObjectName.ConnectionString = "ProviderString;SourceString" Example: mconPayables.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\TaraStore.mdb" The ConnectionString Property (Page 2)

56 The CommandText Property For the OleDbCommand object, a String that defines the SQL SELECT, INSERT, UPDATE, or DELETE command Format: CommandObjectName.CommandText = "SQLCommandString"/StringVariable Example: pcmdVendor.CommandText = "SELECT * FROM Products"

57 The Connection Property For the OleDbCommand object, stores information about the DBMS to which the command references Effectively creates the link between the Command object and the Connection object Format: CommandObjectName.Connection = ConnectionObjectName Example: cmdProducts.Connection = conTaraStore

58 The SelectCommand Property For the OleDbDataAdaptor object, stores SQL SELECT command information to be executed by the DBMS Effectively creates a link between the DataAdaptor object and the Command object Format: DataAdaptorObjectName.SelectCommand = CommandObjectName Example: daProducts.SelectCommand = cmdProducts

59 The Fill Method A method of OleDbDataAdapter objects which: – Opens the connection to the data provider (DBMS) – Sends the SQL SELECT command – After the data provider executes the command, populates DataSet with table data from database Format: DataAdapterObjectName.Fill (DataSetObjectName) Example: daProducts.Fill(dsProducts)

60 The Tables Collection (Page 1) A member of the DataSet object representing the one or more tables assigned to it A collection is an array of properties for an individual object The Tables collection is the set of tables that is stored in the DataSet object and may include one or more tables

61 The Tables Collection (Page 2) Format: DataSetObjectName.Tables(index) Example: mdtVendor = mdsVendor.Tables(0) – Here one table from the DataSet collection is assigned to a DataTable object – The index "0" is the first table from the DataSet (points to a table)

62 TaraStore.mdb—The Products Table

63 DataGridDisplay.aspx

64 Common Database Error Messages ASP.NET Machine account – MachineName\ASPNET – Used by the Web server to run ASP.NET pages – Does not have NTFS permissions to manage the database – Go to Windows Explorer to the file – Set NTFS permissions to Modify

65 Common Database Error Messages (continued)

66 Microsoft Access Database Connection Error Messages Permission to the directory that contains the file – Creates a Microsoft Access LDB file, i.e. Databasename.ldb Record locking and other settings can be set within Access

67 Microsoft Access Database Connection Error Messages (continued)

68

69 Modifying Data Columns in the DataGrid Control (Page 1) By default all columns are displayed in a DataGrid since the AutoGenerateColumns properties is set to True When configuring a data source (DataSet, DataTable, or DataView) programmatically, the DataGrid columns are not created until the code executes

70 Modifying Data Columns in the DataGrid Control (Page 2) The … control block can be used to add columns manually to the HTML view – Set DataField property for each to fieldname from the table – Modify HeaderText property for each column to vary it from default string which is fieldname Example: <asp:BoundColumn …

71 TaraStore.mdb—The Categories Table

72 DisplayGridColumns.aspx

73 The Control (Page 1) Columns have a header, footer, and item section When the control is embedded in an, developer may format that column for every row in the table by setting properties and values using IntelliSense Inserted into either: – The … block format all columns in all rows (but not headers and footers) – The … block to format individual columns

74 The Control (Page 2) Example:

75 The Property Builder for the DataGrid (Page 1) Style template controls (,, etc.) may be inserted into the HTML code for a DataGrid using the Property Builder If data source configured programmatically, remember to first create a … block with controls in the HTML view

76 The Property Builder for the DataGrid (Page 2) Right click on the DataGrid and select Property Builder… from the shortcut menu Select the Columns tab to add columns to and/or modify existing columns in the DataGrid control – Modify each column’s HeaderText, DataField, and other attributes here – A control should appear in the Select columns: list for each column

77 The Property Builder for the DataGrid (Page 3) Select the Format tab to modify the appearance of template items, including: – Header and Footer (top and bottom of grid), and Pager (controls that link to previous and next pages in DataGrid) – Items—adds formatting for rows within the … block including Normal (formats control for all columns) – Columns—drill down clicking the plus (+) in each column to reach its Header and Footer (for each column) or Items (the cells) elements Select the column name to modify its width attribute

78 DisplayGridColumns.aspx— Property Builder Properties (Page 1) Columns tab – CategoryName—HeaderText:"Name" – CategoryID—HeaderText:"Category ID"

79 DisplayGridColumns.aspx— Property Builder Properties (Page 2) Format tab – Header BackColor:DarkSlateGrey Bold:True Font name:Trebuchet MS ForeColor:White Horizontal alignment:Center – Items—Normal Items Font name:Trebuchet MS Font size:X-Small – Columns—Columns(0)—Items Horizontal align: Center

80 Data Columns All of the following are column types that may be inserted within a … block to assign columns to a DataGrid: – BoundColumn—binds the column to one field from a data source – TemplateColumn—customized columns; can be used for formatting how entries appear both while both displaying and editing data in a DataGrid control – HyperLinkColumn—displays and creates a hyperlink (may be configured in the Property Builder)

81 The HyperLinkColumn In place of NavigateURL, the following attributes may be used to pass a query string to a called page – DataNavigateUrlFormatString attribute —the format of a URL with a query string that may store a variable value – DataNavigateUrlField attribute —stores a value which can be passed along with the key as part of the query string Example:

82 DataGridDetails.aspx

83 Column Styles These templates may be modified manually in the HTML view, or by using the Property Builder – HeaderStyle—formats the HeaderTemplate – FooterStyle—formats the FooterTemplate – ItemStyle—formats individual columns in every row – AlternatingItemStyle—formats every other row – SelectedItemStyle—formats currently selected row – EditItemStyle—formats the row in edit mode – PagerStyle—formats the page navigation controls PageSize—stores the number of rows number displayed

84 RepeaterTemplate.aspx

85 Additional Properties for the DataList Control RepeatColumns property—an integer which specifies the number of columns that may be displayed in the DataList for each of the elements RepeatDirections property—direction of repetition for the RepeatColumns property in columns within the grid – RepeatDirection.Horizontal – RepeatDirection.Vertical

86 DataListTemplate.aspx

87


Download ppt "Data-Aware Controls in ASP.NET ® Applications ASP.NET."

Similar presentations


Ads by Google