it533 lectures databinding controls. installations microsoft® sql server® 2012 express download...

48
IT533 Lectures DataBinding Controls

Upload: cecilia-harper

Post on 30-Dec-2015

225 views

Category:

Documents


4 download

TRANSCRIPT

IT533 Lectures

DataBinding Controls

InstallationsMicrosoft® SQL Server® 2012 ExpressDownload the sample sql script files from the course’s

web site CodeWeek3.zip.Run them on the SQL Server Express.

In SQL Server Management Studio, open the .sql script files.

Click Execute on the script files.

Data BindingHow to Populate Server Controls?

Specify the data in the control’s tagsNot dynamic: can’t get data from a database

Write code that uses the control’s object modelThis is okay if you need to populate a simple value or

list, but quickly gets too complicated for populating sophisticated displays

Data bindingCreate an object that holds the data

(DataSet, Array, string, int, etc.)Associate that object with the control

Data BindingWhat Is It?

Provides a single simple yet powerful way to populate Web Form controls with dataEnables clean separation of code from UI

Supports binding to any data sourceProperties, expressions, method callsCollections (Array, Hashtable, etc.)DataSet, DataTable, DataView, DataReaderXML

One way snapshot modelRequires code to reapply to data model

Data BindingWhat Is It?

Allows you to specify an expressionWhen the appropriate DataBind method is called,

the expression is evaluated and boundPage.DataBindDataBind for a single control (and subcontrols)

Works for scalars, e.g. Label controlWorks for lists, e.g. DropDown control, ListBox control, etc.

Enables the use of templates

Data BindingScalar Expressions

Data binding expression: <%# 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();}

Data BindingScalar Expressions

Demo: DataBinding1.aspxData binding to simple, scalar expressions

Data BindingSimple Lists

Data binding can be used to populate list controls, e.g.<asp:ListBox><asp:DropDownList><asp:RadioButtonList><asp:CheckBoxList>

Data BindingSimple Lists

Steps to data bind a list controlDeclare the list controlOptionally set DataValueField and DataTextField

Set its DataSourceCall DataBind() method

Data BindingSimple ListsDemo: DataBinding2.aspx

Data binding to simple lists

Introduction to ADO.NET.NET’s Database FrameworkA data-access technology that enables applications to

connect to data stores and manipulate data contained in them in various ways .

ADO.NET Architecture

ADO.NET Core Objects

Object Description

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

Connected Data Access Model

Disconnected Data Access Model

Pros and Cons

Connected Disconnected

Database Resources

- +

Network Traffic - +Memory Usage + -Data Access - +

Steps of Data Access: Disconnected EnvironmentDefining the connection stringDefining the connection Defining the commandDefining the data adapterCreating 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

Steps of Data Acces : Connected EnvironmentCreate connectionCreate command (select-insert-update-delete)Open connectionIf SELECT -> use a DataReader to fetch dataIf UPDATE, DELETE, INSERT use command

object’s methodsClose connection

Data BindingData 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}

Data BindingData 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();

Data BindingDatabase

Data binding can be used to populate server controls with data from a database

Bind to a DataView of a DataSetSpecify value and text with DataValueField and DataTextField, respectively

Data BindingList Binding Examples

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

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

Data BindingBinding to a Database

Demo: DataBinding3.aspxData binding to a database

Choosing a DataReader or a DatasetThe type of functionality application requires

should be consideredUse 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

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

<connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=.\SQLEXPRESS; database=Northwind; integrated security=true; Trusted_Connection=True"

providerName="System.Data.SqlClient" /></connectionStrings>

• 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

Data Binding GridView

Full-featured list outputDefault look is a gridColumns can be formatted with templates

AutoFormat is availableOptional pagingUpdateable

Data BindingBinding to All Columns

void Page_Load(object s, EventArgs e) { myGridView.DataSource = GetEmployeeData (); myGridView.DataBind();}

<asp:GridView id=myGridView runat="server" />

Binding all columns in the datasourceDeclare an <asp:GridView>Set its DataSourceCall DataBind()

Data BindingBinding to Specific Columns

http://www.asp.net/learn/data-access/tutorial-12-cs.aspx

By default, GridView will display all columnsTo control columns to display:

Set AutoGenerateColumns=“false”Specify Columns propertyAdd column definition

BoundFieldTemplateFieldButtonField, CheckBoxFieldHyperlinkField, ImageFieldCommandField

Data BindingBinding to Specific Columns

<asp:GridView id=myGridView autogeneratecolumns=false runat=server> <Columns> <asp:BoundField DataField="fname"

HeaderText="Name" /> <asp:BoundField DataField="lname"

HeaderText="LastName" /> </Columns> </asp:GridView>

Binding to specific columns in the datasourceDeclare an <asp:GridView>Declare its Columns collectionSet its DataSourceCall its DataBind() method

Data BindingTemplates

Templates provide a powerful way to customize the display of a server control Customize structure – not just styleCan use controls or other HTML within a template3rd party controls can expose new templates

With data binding, templates specify a set of markup (HTML or server controls) for each bound piece of dataNot just specifying formatting and style for a column

However, templates are not limited to data bindingNo fixed set of templatesControls may define their own and expose any number of them

Data BindingTemplates

Standard templates for list-bound controlsHeaderTemplate: rendered once before all data

bound rowsItemTemplate: rendered once for each row in the

data sourceAlternatingItemTemplate: like ItemTemplate, but when present is used for every other row

SeparatorTemplate: rendered between each rowFooterTemplate: rendered once, after all data

bound rows

Data BindingData Binding in Templates

Templates need to access the bound data Container is an alias for the template’s containing

controlDataItem is an alias for the current row of the

datasourceDataBinder.Eval is a utility function provided to

retrieve and format data within a template

<%# DataBinder.Eval(Container.DataItem, "price", "$ {0}") %>

Data BindingRepeater Control

Provides simple output of a list of itemsNo inherent visual formTemplates provide the visual formNo pagingCan provide templates for separatorsNot updateable

Data BindingRepeater Control

<asp:Repeater id="repList" runat="server"><template name="HeaderTemplate"> <table> <tr><td>Title</td><td>Type</td></tr></template>

<template name="ItemTemplate"> <tr> <td><%# DataBinder.Eval(Container.DataItem,"title_id") %></td> <td><%# DataBinder.Eval(Container.DataItem,"type") %></td> </tr></template>

<template name="FooterTemplate"> </table></template></asp:Repeater>

Data BindingDataList Control

Provides list output with editingDefault look is a tableCustomized via templatesDirectional rendering (horizontal or vertical)Single and multiple selectionAlternate itemUpdateableNo paging

Data BindingDataList Control

void Page_Load(object s, EventArgs e) { myDataList.DataSource = GetSampleData(); myDataList.DataBind();}

<asp:datalist id=myDataList runat=server> <template name="itemtemplate"> <b>Title id:</b> <%# DataBinder.Eval(Container.DataItem, "title_id") %> <br> <b>Title:</b> <%# DataBinder.Eval(Container.DataItem, "title") %> </template></asp:datalist>

Data BindingRepeater and DataList Demo

Demo: DataBinding6.aspxUsing templates and data binding to a database with Repeater and DataList controls

Data Binding Deciding When to Use the

GridView, DataList or RepeaterGridView provides the greatest feature set and simplest

Allow the end-user to sort, page, and editDataList provides more control over the look and feel of the

displayed data than the GridView Requires more development time

Repeater allows for complete and total control of the rendered HTML markupNo built-in editing, sorting, or paging supportThe best performance of the three data Web controls

http://msdn.microsoft.com/en-us/library/aa479015.aspx

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

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

Newest DataBinding ControlListView

Let’s do it:ListViewDataBinding.aspx

ASP.NET MVC FrameworkMVC is one of three ASP.NET programming models.MVC is a framework for building web applications

using a Model View Controller design.MVC forces you to separate web 3 different

applications into 3 components:Models for data

Ex: a list of database recordsViews for displaying the data

Ex: a GridView or an HTML table controlControllers for handling the input

Ex: update or insert a new record into a database

MVC Framework AdvantagesThe MVC separation helps you manage complex

applications, because you can focus on one aspect a time. For example, you can focus on the view without depending

on the business logic. It also makes it easier to test an application.

The MVC separation also simplifies group development. Different developers can work on the view, the controller

logic, and the business logic in parallel.Integrated with all existing ASP.NET features such as

Master Pages, Security, and Authentication.Full control over HTML, CSS, and JavaScript.

MVC Framework ModelModels both hold and manipulate application data.Database might exist or can be created automatically.Model MovieDB.cs:using System.Web;using System.Data.Entity;

namespace MvcDemo.Models{

public class MovieDB{

public int ID { get; set; }public string Title { get; set; }public string Director { get; set; }public DateTime Date { get; set; }

}public class MovieDBContext : DbContext{

public DbSet<MovieDB> Movies { get; set; } }

}

MVC Framework ViewLets you select any of the following View options:

Internet Application templateRazor EngineHTML5 Markup

Razor is a new markup with .cshtml extension<!DOCTYPE html><html> <head><meta charset="utf-8" /><title>@ViewBag.Title</title><link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"/><script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script><script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></script></head><body><ul id="menu"><li>@Html.ActionLink("Home", "Index", "Home")</li><li>@Html.ActionLink("Movies", "Index", "Movies")</li><li>@Html.ActionLink("About", "About", "Home")</li> </ul> <section id="main">@RenderBody()</section> </body> </html>

MVC Framework ControllerMVC maps URLs to methods.

These methods are in classes called "Controllers".Controllers are responsible for processing incoming requests, handling

input, saving data, and sending a response to send back to the client.The Home controller defines the two controls Index and About:

using System.Web;using System.Web.Mvc;

namespace MvcDemo.Controllers{

public class HomeController : Controller{

public ActionResult Index(){return View();}

public ActionResult About(){return View();}

}}

MVC Demo 1 : MVCTestModel: EmployeeView: Home\Index.cshtmlController: HomeController

MVC Demo 2 : MVCTestModel: Employee, DepartmentView: All.cshtml, Index.cshtmlController: EmployeeController