Está en la página 1de 14

Data binding

Data binding
• In ASP.NET, the term Data Binding implies binding the controls to data
that is retrieved from the data source and hence providing a read or
write connectivity between these controls and the data, that they are
bound to.
• These data sources can be one of databases, xml files or even, flat
files.
• Data binding establishes a connection between the application UI and
business logic.
• Two types:
• Single value
• Repeated value
Single value binding
• Single value data binding implies, binding of a single value or a single record, say, an employee's record.
• You can use single-value data binding to add information anywhere on an ASP.NET page.
• You can even place information into a control property or as plain text inside an HTML tag.
• Single-value data binding allows you to take a variable, a property, or an expression and insert it dynamically
into a page
• To use it, you add special data-binding expressions into your .aspx files. These expressions have the following
format:
<%# expression_goes_here %>
• For example, if you have a public or protected variable named Country in your page, you could write the
following:
<%# Country %>
• When you call the DataBind() method for the page, this text will be replaced with the value for Country (for
example, Spain).
Similarly, you could use a property or a built-in ASP.NET object as follows:
<%# Request.Browser.Browser %>
A Simple Data-Binding Example
• Consider a variable TransactionCount defined in your Page class
public partial class SimpleDataBinding : System.Web.UI.Page
{
protected int TransactionCount;
}
• Assume that this value is set in the Page.Load event handler
protected void Page_Load(object sender, EventArgs e)
{
TransactionCount = 10;
this.DataBind();
}
• Two actions take place in this event handler: the TransactionCount variable is set
to 10, and all the databinding expressions on the page are bound.
• To add your expression, find the tag for the Label control. Modify the text inside
the label as shown here:
<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>
A Simple Data-Binding Example
• This example uses two separate data-binding expressions
• The first data-binding expression references the TransactionCount
variable, and the second uses the built-in Request object to
determine some information about the user’s browser.
• Output looks like this:
Repeated-Value Data Binding
• Repeated-value data binding allows you to display an entire table (or just a single field
from a table).
• Unlike single-value data binding, this type of data binding requires a special control that
supports it.
• Typically, this is a list control such as CheckBoxList or ListBox, or other types of Data
controls such as a GridView
• A control that supports repeated-value data binding provides a DataSource property.
• Repeated value binding can also be used to bind data from a collection or an array.
• Following are the controls that supports repeated value binding:
1. ListBox, DropDownList, CheckBoxList, and RadioButtonList
2. HtmlSelect
3. GridView, DetailsView, FormView, and ListView
Data Binding with Simple List Controls
Steps:
• Create and fill some kind of data object that supports collections such
as an array, basic ArrayList and Hashtable,List and Dictionary
collections, and the DataTable and DataSet objects
• Link the object to the appropriate control.Set a couple of properties,
including DataSource.
• Activate the binding using DataBind() method
A Simple List-Binding Example
• Add a ListBox control to a new web page. Then use the Page.Load event handler to create a
strongly typed List collection to use as a data source:
List<string> fruit = new List<string>();
fruit.Add("Kiwi");
fruit.Add("Pear");
fruit.Add("Mango");
fruit.Add("Blueberry");
fruit.Add("Apricot");
fruit.Add("Banana");
fruit.Add("Peach");
fruit.Add("Plum");
• Now link this collection to the ListBox control:
ListBox1.DataSource=fruit;
• To activate the binding, use the DataBind() method:
this.DataBind();
or
ListBox1.DataBind() to bind just the ListBox control.
Data Binding with ADO.NET
• When you’re using data binding with the information drawn from a database, the data-binding process takes
place in the same three steps. First you create your data source, which will be a DataReader or DataSet
object.
• The next example creates a DataSet and binds it to a list(instead of this example you can also write example
given in prac no.8c )
// Define a DataSet with a single DataTable.
DataSet ds = new DataSet();
ds.Tables.Add("Users");

// Define two columns for this table.


ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Country");

// Add some actual information into the table.


DataRow row1 = ds.Tables["Users"].NewRow();
row1["Name"] = "John";
row1["Country"] = "Uganda";
dsInternal.Tables["Users"].Rows.Add(row1);

DataRow row2 = ds.Tables["Users"].NewRow();


row2 = dsInternal.Tables["Users"].NewRow();
row2["Name"] = "Samantha";
row2["Country"] = "Belgium";
ds.Tables["Users"].Rows.Add(row2);
• Next you bind the DataTable from the DataSet to the appropriate
control.
lstUser.DataSource = dsInternal.Tables["Users"];
• The last step is to activate the binding:
this.DataBind();
Working with Data Source
Controls
Data Source controls
• Data source controls allow you to create data-bound pages without writing any data access code
at all.
• The data source controls include any control that implements the IDataSource interface.
• The .NET Framework includes the following data source controls:
1. SqlDataSource: This data source allows you to connect to any data source that has an ADO.NET
data provider. This includes SQL Server, Oracle, and OLE DB or ODBC datasources
2. AccessDataSource: This data source allows you to read and write the data in an Access
database file (.mdb)
3. ObjectDataSource: This data source allows you to connect to a custom data access class.
4. XmlDataSource: This data source allows you to connect to an XML file.
5. SiteMapDataSource: This data source allows you to connect to a .sitemap file that describes
the navigational structure of your website
6. LinqDataSource: This data source allows you to query a database by using the LINQ to SQL
feature
The SqlDataSource
• Data source controls turn up in the .aspx markup portion of your web
page like ordinary controls. For example:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ... />
• The SqlDataSource represents a database connection that uses an
ADO.NET provider
• .NET includes a data provider factory for each of its four data
providers:
1. System.Data.SqlClient
2. System.Data.OracleClient
3. System.Data.OleDb
4. System.Data.Odbc
• The next step is to supply the required connection string
• To refer to a connection string in your .aspx markup, you use a special syntax in this format:
<%$ ConnectionStrings:[NameOfConnectionString] %>
• you would specify it in the SqlDataSource by using this syntax:
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Northwind %>" ... />
• The next step is to add the query logic that the SqlDataSource will use when it connects to the database.
• You can use each SqlDataSource control you create to retrieve a single query. Optionally, you can also add
corresponding commands for deleting, inserting, and updating rows.
• The SqlDataSource command logic is supplied through four properties—SelectCommand, InsertCommand,
UpdateCommand, and DeleteCommand.
• For Ex: Here’s a complete SqlDataSource that defines a Select command for retrieving product information
from the Products table:
<asp:SqlDataSource ID="sourceProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT ProductName, ProductID FROM Products"
/>
• After you make these changes, you’ll wind up with a control tag like this:
<asp:DropDownList ID="lstProduct" runat="server" AutoPostBack="True"
DataSourceID="sourceProducts" DataTextField="ProductName"
DataValueField="ProductID" />