Presentation is loading. Please wait.

Presentation is loading. Please wait.

IT533 Lectures DataBinding Controls. Installations Microsoft® SQL Server® 2008 Express Download the sample MDF files from the course’s web site CodeWeek3.zip.

Similar presentations


Presentation on theme: "IT533 Lectures DataBinding Controls. Installations Microsoft® SQL Server® 2008 Express Download the sample MDF files from the course’s web site CodeWeek3.zip."— Presentation transcript:

1 IT533 Lectures DataBinding Controls

2 Installations Microsoft® SQL Server® 2008 Express Download the sample MDF files from the course’s web site CodeWeek3.zip. Attach them to the SQL Server Express. In SQL Server Management Studio, right click on Databases. Click Attach and then Add, select the MDF file.

3 Data Binding How to Populate Server Controls? Specify the data in the control’s tags Not dynamic: can’t get data from a database Write code that uses the control’s object model This is okay if you need to populate a simple value or list, but quickly gets too complicated for populating sophisticated displays Data binding Create an object that holds the data ( DataSet, Array, string, int, etc.) Associate that object with the control

4 Data Binding What Is It? Provides a single simple yet powerful way to populate Web Form controls with data Enables clean separation of code from UI Supports binding to any data source Properties, expressions, method calls Collections ( Array, Hashtable, etc.) DataSet, DataTable, DataView, DataReader XML One way snapshot model Requires code to reapply to data model

5 Data Binding What Is It? Allows you to specify an expression When the appropriate DataBind method is called, the expression is evaluated and bound Page.DataBind DataBind for a single control (and subcontrols) Works for scalars, e.g. Label control Works for lists, e.g. DropDown control, ListBox control, etc. Enables the use of templates

6 Data Binding Scalar Expressions Data binding expression: Expression is evaluated when DataBind() is called <asp:Label id=label1 Text=<%# “The result is “ + (1 + 2) + “, the time is “ + DateTime.Now.ToLongTimeString() %> runat="server" /> public void Page_Load(object s, EventArgs e) { if (! Page.IsPostBack) Page.DataBind(); }

7 Data Binding Scalar Expressions Demo: DataBinding1.aspx Data binding to simple, scalar expressions

8 Data Binding Simple Lists Data binding can be used to populate list controls, e.g.

9 Data Binding Simple Lists Steps to data bind a list control Declare the list control Optionally set DataValueField and DataTextField Set its DataSource Call DataBind() method

10 Data Binding Simple Lists Demo: DataBinding2.aspx Data binding to simple lists

11 Introduction to ADO.NET.NET’s Database Framework A data-access technology that enables applications to connect to data stores and manipulate data contained in them in various ways.

12 ADO.NET Architecture

13 ADO.NET Core Objects ObjectDescription Connection Establishes a connection to a specific data source. (Base class: DbConnection) Command Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection. (The base class: DbCommand) DataReader Reads a forward-only, read-only stream of data from a data source. (Base class: DbDataReader) DataAdapter Populates a DataSet and resolves updates with the data source. (Base class: DbDataAdapter) DataTable Has a collection of DataRows and DataColumns representing table data, used in disconnected model DataSet Represents a cache of data. Consists of a set of DataTables and relations among them

14 Connected Data Access Model

15 Disconnected Data Access Model

16 Pros and Cons ConnectedDisconnected Database Resources -+ Network Traffic -+ Memory Usage +- Data Access -+

17 Steps of Data Access: Disconnected Environment Defining the connection string Defining the connection Defining the command Defining the data adapter Creating a new DataSet object SELECT -> fill the dataset object with the result of the query through the data adapter Reading the records from the DataTables in the datasets using the DataRow and DataColumn objects UPDATE, INSERT or DELETE -> update the database through the data adapter

18 Steps of Data Acces : Connected Environment Create connection Create command (select-insert-update-delete) Open connection If SELECT -> use a DataReader to fetch data If UDATE,DELETE, INSERT -> use command object’s methods Close connection

19 Data Binding Data Source Example DataView GetSampleData() { DataSet ds; SqlConnection cxn; SqlDataAdapter adp; cxn = new SqlConnection("server=localhost; " + "uid=sa;pwd=;database=Northwind"); adp = new SqlDataAdapter( "select CategoryID, CategoryName from Categories", cxn); ds = new DataSet(); adp.Fill(ds, "Categories"); return ds.Tables["Categories"].DefaultView; // Work on the data in memory using the DataSet (ds) object }

20 Data Binding Data Source Example // Databind the list box to a data reader SqlConnection cxn = new SqlConnection("Data Source=.\\SQLEXPRESS;database=Northwind; integrated security=true; Trusted_Connection=True"); SqlCommand cmd = new SqlCommand("select CategoryID, CategoryName from Categories", cxn); cxn.Open(); SqlDataReader dr = cmd.ExecuteReader(); CheckBoxList1.DataSource = dr; CheckBoxList1.DataValueField ="CategoryID"; CheckBoxList1.DataTextField="CategoryName"; CheckBoxList1.DataBind(); cxn.Close();

21 Data Binding Database Data binding can be used to populate server controls with data from a database Bind to a DataView of a DataSet Specify value and text with DataValueField and DataTextField, respectively

22 Data Binding List Binding Examples void Page_Load(object s, EventArgs e) { ListBox1.DataSource = GetSampleData(); ListBox1.DataValueField = "CategoryID"; ListBox1.DataTextField = "CategoryName"; ListBox1.DataBind(); } void Page_Load(object s, EventArgs e) { ListBox1.DataBind(); } <asp:ListBox id="ListBox1" runat="server" DataSource= DataValueField=“CategoryID” DataTextField=“CategoryName” />

23 Data Binding Binding to a Database Demo: DataBinding3.aspx Data binding to a database

24 Choosing a DataReader or a Dataset The type of functionality application requires should be considered Use a DataSet to: Cache data locally in your application so that you can manipulate it Remote data between tiers or from an XML Web service Interact with data dynamically such as combining and relating data from multiple sources Perform extensive processing on data without requiring an open connection to the data source, which frees the connection to be used by other clients If readonly data is needed use DataReader to boost performance

25 Best Practices Don’t create a new connection string for every code connecting to DB Use web.config file to keep your connection strings through the application scope <add name="NorthwindConnectionString" connectionString="Data Source=.\SQLEXPRESS; database=Northwind; integrated security=true; Trusted_Connection=True" providerName="System.Data.SqlClient" />  Use WebConfigurationManager.OpenWebConfiguration, ConnectionStringSettings to access settings at runtime. Let’s modify DataBinding3.aspx.cs You can keep any other variable to reach at runtime using this technique

26 Data Binding GridView Full-featured list output Default look is a grid Columns can be formatted with templates AutoFormat is available Optional paging Updateable DataGrid vs GridView http://www.codeproject.com/KB/webforms/GridView _all_in_one.aspx http://www.codeproject.com/KB/webforms/GridView _all_in_one.aspx

27 Data Binding Binding to All Columns void Page_Load(object s, EventArgs e) { myDataGrid.DataSource = GetEmployeeData (); myDataGrid.DataBind(); } Binding all columns in the datasource Declare an Set its DataSource Call DataBind()

28 Data Binding Binding to Specific Columns By default, GridView will display all columns To control columns to display: Set AutoGenerateColumns=“false” Specify Columns property Add column definition BoundField TemplateField (http://www.asp.net/learn/data- access/tutorial-12-cs.aspx)http://www.asp.net/learn/data- access/tutorial-12-cs.aspx ButtonField, CheckBoxField HyperlinkField, ImageField CommandField (Edit, Select, Delete)

29 Data Binding Binding to Specific Columns <asp:datagrid id=myDataGrid autogeneratecolumns=false runat=server> <asp:BoundField DataField="fname" HeaderText="Name" /> <asp:BoundField DataField="lname" HeaderText="LastName" /> Binding to specific columns in the datasource Declare an Declare its Columns collection Set its DataSource Call its DataBind() method

30 Data Binding GridView Paging Do this as an EXERCISE at home When there is too much data to display in one screen, a GridView can provide automatic paging Set AllowPaging=“true” Handle OnPageIndexChanged event Set page index Fetch data Re-bind data Handle OnPageIndexChanging event

31 Data Binding Templates Templates provide a powerful way to customize the display of a server control Customize structure – not just style Can use controls or other HTML within a template 3 rd party controls can expose new templates With data binding, templates specify a set of markup (HTML or server controls) for each bound piece of data Not just specifying formatting and style for a column However, templates are not limited to data binding No fixed set of templates Controls may define their own and expose any number of them

32 Data Binding Templates Standard templates for list-bound controls HeaderTemplate : rendered once before all data bound rows ItemTemplate : rendered once for each row in the data source AlternatingItemTemplate : like ItemTemplate, but when present is used for every other row SeparatorTemplate : rendered between each row FooterTemplate : rendered once, after all data bound rows

33 Data Binding Data Binding in Templates Templates need to access the bound data Container is an alias for the template’s containing control DataItem is an alias for the current row of the datasource DataBinder.Eval is a utility function provided to retrieve and format data within a template

34 Data Binding Repeater Control Provides simple output of a list of items No inherent visual form Templates provide the visual form No paging Can provide templates for separators Not updateable

35 Data Binding Repeater Control Title Type

36 Data Binding DataList Control Provides list output with editing Default look is a table Customized via templates Directional rendering (horizontal or vertical) Single and multiple selection Alternate item Updateable No paging

37 Data Binding DataList Control void Page_Load(object s, EventArgs e) { myDataGrid.DataSource = GetSampleData(); myDataGrid.DataBind(); } Title id: Title:

38 Data Binding Repeater and DataList Demo Demo: DataBinding6.aspx Using templates and data binding to a database with Repeater and DataList controls

39 Data Binding Deciding When to Use the GridView, DataList or Repeater http://msdn.microsoft.com/en-us/library/aa479015.aspx http://www.dotnet- friends.com/fastcode/asp/fastcodeinasp140ee486-9653-4807-bf04- aee4d5696991.aspx http://www.dotnet- friends.com/fastcode/asp/fastcodeinasp140ee486-9653-4807-bf04- aee4d5696991.aspx

40 40 ASP.NET 3.5 introduces two new server-side data controls, the ListView and the DataPager. The ListView is highly customizable control for displaying data. You can define an assortment of templates such as ItemsTemplate, SelectedItemTemplate, ItemSeparatorTemplate, and GroupTemplate to customize how to display data. Includes styling with CSS, flexible pagination, and sorting, inserting, deleting, and updating features. New ASP.NET 3.5 Data Binding Controls ListView and DataPager

41 41 The DataPager control works alongside a data control, such as GridView or ListView, and customizes how it pages through data. With a data pager, you can customize the combination of page-navigation buttons (such as next, previous, or page numbers) that are displayed. New ASP.NET 3.5 Data Binding Controls ListView and DataPager

42 Newest DataBinding Control ListView Example that I learned from: http://www.codeproject.com/KB/webforms/CompleteListView.aspx Let’s do it: ListViewDataBinding.aspx


Download ppt "IT533 Lectures DataBinding Controls. Installations Microsoft® SQL Server® 2008 Express Download the sample MDF files from the course’s web site CodeWeek3.zip."

Similar presentations


Ads by Google