Wednesday, December 14, 2011

ASP .net Data Binding

Data binding at first is a mechanism  by which you can bind, synchronize or link data with user interface (controls).
In ASP.net there are two types of data binding:
  1. Single-Value (Simple) Data Binding
  2. Repeated-Value (List) Data Binding
Single-Value Data binding

Allows you to take a variable, a value returned by a method or an expression and place it dynamically inside the user interface of a webform.

Syntax:    <%# your_expression %> 
this example can be a footer on a website 
<div style="text-align:center;">
    CopyRight &copy;<%#DateTime.Now.Year %>. Nuux
</div>
      the output should look like:
                              CopyRight©2011. Nuux
Note that the year is not constant it will change with the server's date.
Data binding to work requires to be activated explicitly. To activate data binding call a method known as Databind() for each control as ctrl.Databind() or once for all controls as Me.Databind() or simply Databind()in which case the owner object is implied as Me (the current page (this in C#)). So call this method in your Page load event like the following example. It is better practice to place the method below your code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Your code goes here
        Me.DataBind()
    End Sub
 If you have got variables or methods you want to show or use their values on your interface make sure they are declared with either of these access modifiers: Public, Protected or Friend. You cannot access objects with private access in your interface.
Control properties can be set by data binding: Try this:
<asp:TextBox id="txt1" runat="server" />
<asp:Label id="labelOne" Text="<%# txt1.Text %>" runat="server" />
<asp:Label id="labelTwo" Text="<%# DateTime.Now %>" runat="server" />

Repeated-Value Data binding
Repeated-Value data binding works with list controls. By the way, there are two types of list controls in asp.net:
  1. Simple List Controls eg: ListBox,DropDownList, RadioButtonList etc
  2. Rich Data List Controls eg: GridView,ListView, DetailsView and FormView
These controls expose a number of properties and methods for data binding purpose.You can bind these controls to almost any structure that support the IEnumerable interface. The data sources for this controls include: Collection,array, arraylist, DataTable, DataView,DataReader, HashTable and DataSet.
Data binding can be done at design time or at runtime. 

For a good explanation this might help you: Data Binding - The Concepts
 

1 comment:

Search This Blog (raadi)