Chapter 15

Post on 20-Jan-2015

1,027 views 4 download

Tags:

description

 

transcript

Data Binding

• Introducing Data Binding

• Types of ASP.NET Data Binding

• Simple-Value

• Repeated-Value

• How Data Binding Works

• A Simple Data Binding Example

• Data Binding with ADO.NET

• Data Source Controls

• How Data Source Controls Work

Data Binding

The process of popping data directly into HTML elements and fully formatted controls is called data binding.

Single Value Data Binding

You can use single-value data binding to add information anywhere on an ASP.NET page.

Single-value data binding allows you to take a variable, a property, or an expression and insert it dynamically into a page.

To use single-value binding, you must insert a data binding expression into the markup in the .aspx file (not the code-behind file).

Example Single Value Binding

<asp:Label id="lblDynamic" runat="server" Font-Size="X-Large">

There were <%# TransactionCount %> transactions today.I see that you are using <%# Request.Browser.Browser %>

</asp:Label>protected void Page_Load(object sender, EventArgs e){

// to look up a value for TransactionCount

TransactionCount = 10;// Now convert all the data binding expressions on the page.this.DataBind();}

In .aspx file

In .cs file

Simple Data Binding with Properties

public partial class DataBindingUrl : System.Web.UI.Page{protected string URL;protected void Page_Load(Object sender, EventArgs e){URL = "Images/picture.jpg";this.DataBind();}}

<asp:Label id="lblDynamic" runat="server"><%# URL %> </asp:Label>

<asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" />

<asp:Hyperlink id="lnkDynamic" Text="Click here!" NavigateUrl="<%# URL %>"runat="server" />

Repeated Value Data Binding

Repeated-value data binding works with the ASP.NET list controls (and the rich data controls described in the next chapter).

To use repeated-value binding, you link one of these controls to a datasource (such as a field in a data table). When you call DataBind(), the control automatically creates a full list using all the corresponding values.

This saves you from writing code that loops through the array ordata table and manually adds elements to a control

Repeated Value Data Binding

To create a data expression for list binding, you need to use a list control that explicitly supports data binding. :

ListBox, DropDownList, CheckBoxList, and RadioButtonList: These web controls provide a list for a single field of information.

HtmlSelect: This server-side HTML control represents the HTML <select> element and works essentially the same way as the ListBox web control. Generally, you’ll use this control only for backward compatibility.

GridView, DetailsView, FormView, and ListView: These rich web controls allow you to provide repeating lists or grids that can display more than one field of information at a time.

Repeated Value Binding Example

ArrayList fruit = new ArrayList();fruit.Add("Kiwi");fruit.Add("Pear");fruit.Add("Mango");

Now, you can link this collection to the ListBox control:lstItems.DataSource = fruit;

this.DataBind();

Repeated Value Binding Example

List<string> fruit = new List<string>();fruit.Add("Kiwi");fruit.Add("Pear");fruit.Add("Mango");fruit.Add("Blueberry");

// Define the binding for the list controls.MyListBox.DataSource = fruit;MyDropDownListBox.DataSource = fruit;MyHtmlSelect.DataSource = fruit;MyCheckBoxList.DataSource = fruit;MyRadioButtonList.DataSource = fruit;// Activate the binding.this.DataBind();

Using the DataValueField Property

<select name="MyListBox" id="MyListBox" ><option value="1">Kiwi</option><option value="2">Pear</option><option value="3">Mango</option></select>

protected void MyListBox_SelectedIndexChanged(Object sender,EventArgs e){lblMessage.Text = "You picked: " + MyListBox.SelectedItem.Text;lblMessage.Text += " which has the key: " + MyListBox.SelectedItem.Value;}

Binding Drop Down List

string selectSQL = "SELECT ProductName, ProductID FROM Products";SqlConnection con = new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand(selectSQL, con);// Open the connection.con.Open();// Define the binding for the drop down list.lstProduct.DataSource = cmd.ExecuteReader();lstProduct.DataTextField = "ProductName";lstProduct.DataValueField = "ProductID";// Activate the binding.this.DataBind();con.Close();// Make sure nothing is currently selected in the list box.lstProduct.SelectedIndex = -1;

Data Binding with ADO.NET

1. First, create the DataSet.

2. Next, create a new DataTable, and add it to the DataSet.Tables collection.

3. Next, define the structure of the table by adding DataColumn objects (one foreach field) to the DataTable.Colums collection.

4. Finally, supply the data. You can get a new, blank row that has the same structure as your DataTable by calling the DataTable.NewRow() method. You must then set the data in all its fields, and add the DataRow to the DataTable.Rows collection.

Data source controls allow you to create data-bound pages without writing any data access code at all.

Data Source Controls

•SqlDataSource: This data source allows you to connect to any data source that has an ADO.NET data provider. When using this data source, you don’t need to write the data access code.• AccessDataSource: This data source allows you to read and write the data in an Access database file (.mdb). •ObjectDataSource: This data source allows you to connect to a custom data access class. This is the preferred approach for large-scale professional web applications, but it forces you to write much more code. • XmlDataSource: This data source allows you to connect to an XML file. You’ll learn more about XML in Chapter 18.• SiteMapDataSource: This data source allows you to connect to a .sitemap file that describes the navigational structure of your website. • EntityDataSource: This data source allows you to query a database using the LINQ to Entities feature, which you’ll tackle in Chapter 24.• LinqDataSource: This data source allows you to query a database using the LINQ to SQL feature, which is a similar (but somewhat less powerful) predecessor to LINQ to Entities.

The SqlDataSource represents a database connection that uses an ADO.NET provider. This includes SQL Server, Oracle, and OLE DB orODBC data sources.

.NET includes a data provider factory for each of its four data providers:• System.Data.SqlClient• System.Data.OracleClient• System.Data.OleDb• System.Data.OdbcYou can use all of these providers with the SqlDataSource.

<asp:SqlDataSource ProviderName="System.Data.SqlClient" ... />

Technically, you can omit this piece of information, because the System.Data.SqlClient provider factory is the default.

The SqlDataSource

<configuration><connectionStrings><add name="Northwind" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI" /></connectionStrings>...</configuration>

<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Northwind %>" ... />

The SqlDataSource

You can use each SqlDataSource control you create, to retrieve a single query.

The SqlDataSource command logic is supplied through four properties—SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand—each of which takes a string.

<asp:SqlDataSource ID="sourceProducts" runat="server"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductID FROM Products“ />

Selecting Records

<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>“

SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"/>

<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID">

<SelectParameters><asp:ControlParameter ControlID="lstProduct" Name="ProductID"PropertyName="SelectedValue" /></SelectParameters></asp:SqlDataSource>

Parameterized Commands

If bound to Rich Controls SqlDataSource can display many fields at a time as compared to List Controls which display only one field at a time.

Example:

GridviewDetailsView

Bind SqlDataSource to Rich Controls

Other Types of Parameters

For example, you could split the earlier example into two pages. In the first page, define a list control that shows all the available products:

<asp:SqlDataSource ID="sourceProducts" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT ProductName, ProductID FROM Products"/>

<asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True"DataSourceID="sourceProducts" DataTextField="ProductName"DataValueField="ProductID" />

Using QueryStringParameter

protected void cmdGo_Click(object sender, EventArgs e){if (lstProduct.SelectedIndex != -1){Response.Redirect("QueryParameter2.aspx?prodID=" + lstProduct.SelectedValue);}}Finally, the second page can bind the DetailsView according to the ProductID value that’s supplied in the query string:

<asp:SqlDataSource ID="sourceProductDetails" runat="server"ProviderName="System.Data.SqlClient"ConnectionString="<%$ ConnectionStrings:Northwind %>"SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID"><SelectParameters><asp:QueryStringParameter Name="ProductID" QueryStringField="prodID" /></SelectParameters></asp:SqlDataSource><asp:DetailsView ID="detailsProduct" runat="server"DataSourceID="sourceProductDetails" />

Using QueryStringParameter