Data Binding in asp.net



                                       Data binding
Data binding  in the context of .Net,is the method by which controls on a user interface(UI) of  a client application are configured to fetch from,or update data into,a data source,such as a database or XML document.
Prior to .NET,access to data binding models were limited to database.thus,many database management system(DBM) could  indirectly access the data source through their application programming interface (API) without any flexibility in controlling the data binding process.
This problem is addressed in .NET by providing fine control of how the data bound and behavior f UI with windows form and ADO.NET classes in the framework.
the development of web application is simplifying by providing data binding capability to web page using .NET server side web controls.


Advantage of data binding in .NET is as follows:-
1-reduction in code size
2-better performance of the application
3-rapid development of data-driven applications
4-customization of default data binding process by modifying the generated code wherever necessary
5-fine control of data binding trough event
6-visual feedback on validation error by associating validation rules of data with built-in type validation of control in (for example data value entered in data control)


                      Data binding to Grid view:-

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="BasicGridView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
   
    </div>
    </form>
</body>
</html>



File: Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;

public partial class BasicGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
            string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM Products";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();

            adapter.Fill(ds, "Products");

            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
}




File: Web.config



<?Xml version="1.0"?>
<Configuration>
  <ConnectionStrings>
    <Add name="Northwind" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI"/>
  </connectionStrings>
</configuration>





Using the BindingManager in order to have  2 way data binding is easy:-


1-add the binding manager component to the toolbox.
2-add a BindingMaanger component to a web form
Use the designer to set the Data Bindings
4-when you need to load the web form with your data call to the Binding Manager’s BindtoWebForm method
5-in order to get the data from the web form,you have to call to binding manager’s bindFromwebForm method


Coding is here-


protected void UpdateDataBindings() 
{
  // create a new collection to store the new bindings found
  DataBindingInfoCollection newBindings = new DataBindingInfoCollection();
 
  // gets all web controls from the form
  IReferenceService service = (IReferenceService)GetService(
    typeof(IReferenceService));
  object[] references = service.GetReferences(typeof(Control));
 
  foreach(Control control in references){
    // if the control isn't in the page but it's a naming container, skip it
    if ((control.NamingContainer == null) || 
       (control.NamingContainer.GetType() != typeof(Page))) continue;
    
    // get the interface related to data binding
    IDataBindingsAccessor dba = (IDataBindingsAccessor)control;
 
    if (dba.HasDataBindings){
      foreach (DataBinding db in dba.DataBindings){
        // get the binding information for the control
        DataBindingInfo dbi = GetBindingInformation(db, control);
 
        // if the entry isn't new, set the old values
        UpdateDataBindingInfo(dbi, bindingManager.DataBindings);
 
        newBindings.Add(dbi);
      }
    }
  }
 
  // if the data bindings have changed
  if (CheckBindingChanges(bindingManager.DataBindings, newBindings)){
    // notify that the component is going to change
    RaiseComponentChanging(null);
 
    // update the bindings
    bindingManager.DataBindings.Clear();
    foreach(DataBindingInfo dbi in newBindings){
      bindingManager.DataBindings.Add(dbi);
    }
 
    // notify that the component has changed
    RaiseComponentChanged(null, null, null);
  }
}
 
 
 
Working of BindingManger :-
 
 







public void BindFromWebForm(Page form) 
{
  // iterate through the data bindings
  foreach (DataBindingInfo dbi in _dbic){
    // if the binding isn't two way, exit
    if (!dbi.TwoWay) continue;
 
    // get property to bind from
    object sourceProp = GetFieldOrPropertyEx(dbi.Control, dbi.PropControl);
    
    // if we can't get the property, error
    if (sourceProp == null) throw new DataBindingException(
        "DataBinding error, can't find: " + dbi.PropControl, dbi.Control);
    
    // get the full property name
    string fullPropObject = dbi.Object;
    if (dbi.PropObject != null){
      fullPropObject += "." + dbi.PropObject;
    }
 
    // check source and destination types
    Type sourcePropType = sourceProp.GetType();
    Type destPropType = GetFieldOrPropertyTypeEx(form, fullPropObject);
 
    if (destPropType == null){
      throw new DataBindingException(
        "DataBinding error, can't find: " + fullPropObject, dbi.Control);
    }
 
    // if the types doesn't match try to make a conversion
    if (!sourcePropType.Equals(destPropType)){
      try {
        sourceProp = ConvertTypes(sourceProp, destPropType);
      } catch (Exception e){
        throw new DataBindingException(
          "DataBinding error, can't convert types: ", e, dbi.Control);
      }
 
      if (sourceProp == null){
        throw new DataBindingException(
         "DataBinding error, can't convert bound property: " + 
          dbi.PropControl + " for: " + fullPropObject, dbi.Control);
      }
    }
    
    // do the data binding
    if (!SetFieldOrPropertyEx(form, fullPropObject, sourceProp)){
      throw new DataBindingException("DataBinding error, can't set: " 
           + fullPropObject, dbi.Control);
    }
  }
}


Comments

Post a Comment

Popular posts from this blog

The Psychology of Money (Vitamin "M")

JQuery