Data Binding in ASP.Net can be categorised into two: simple databinding and declarative databinding. Some controls support at least simple databinding while others support both. Simple databinding basically involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control. Calling DataBind on the page or the control is a must in simple databinding.


Introduction:

Data Binding in ASP.Net can be categorised into two: simple databinding and declarative databinding. Some controls support at least simple databinding while others support both. Simple databinding basically involves attaching any collection (item collection) which implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control. Calling DataBind on the page or the control is a must in simple databinding.

The controls supporting the more complex databinding include a property named DataSourceID. Unlike the simple databinding which involves basically iterating through a collection, the declarative databinding classes use separate Data controls capable of managing data for the databound controls. These data managers help the databound controls implement functionalities like, sorting, paging and editing data collections. There are several DataSource controls for working with different data sources like XML data, Access databases, SQL Server etc. In this kind of databinding calling DataBind is optional as the controls call DataBind during PreRendering event. Declarative databinding in ASP.Net 2.0 upwards has simplified the process of rendering tremendously. We will check this a little later.

Type of Data Binding and controls involved:

Simple databinding: ListBox, DropDownList, RadioButtonList, CheckButtonList and other controls based on ListControl

Declarative databinding: ListControl based controls, TreeView, Menu, FormView, GridView, DetailsView, DataList, and Repeater.

Simple Data Binding:

We will discuss simple databinding with the help of a simple application. In this application, we have created a booklist class. This class have two string attributes a title (bookname) and author (authorname). On the page we have used four databound controls: a ListBox, a DropDownList, a RadioButtonList, and a CheckButtonList. With each such control there will be a label to show the selected value from the list. The application is self-explanatory and you can download it.

The class booklist looks like:

public class booklist
{
    protected String bookname;
    protected String authorname;
 public booklist(String bname, String aname)
 {
        this.bookname = bname;
        this.authorname = aname;

 }
    public String Book
    {
        get
        {
            return this.bookname;
        }
        set{
            this.bookname = value;
        }
    }
    public String Author
    {
        get
        {
            return this.authorname;
        }
        set
        {
            this.authorname = value;
        }
    }
}

The code behind the page:

protected void Page_Load(object sender, EventArgs e)
    {
        IList bklist = createbooklist();
        if (!this.IsPostBack)
        {
            this.ListBox1.DataSource = bklist;
            this.ListBox1.DataTextField = "Book";
            this.ListBox1.DataValueField = "Author";
            this.DropDownList1.DataSource = bklist;
            this.DropDownList1.DataTextField = "Book";
            this.DropDownList1.DataValueField = "Author";
            this.RadioButtonList1.DataSource = bklist;
            this.RadioButtonList1.DataTextField = "Book";
            this.RadioButtonList1.DataValueField = "Author";
            this.CheckBoxList1.DataSource = bklist;
            this.CheckBoxList1.DataTextField = "Book";
            this.CheckBoxList1.DataValueField = "Author";
            this.DataBind();
        }
    }
    protected IList createbooklist()
    {
        ArrayList allbooks = new ArrayList();
        booklist bl;
        bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");
        allbooks.Add(bl);
        bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");
        allbooks.Add(bl);
        bl = new booklist("DATA STRUCTURE", "TANENBAUM");
        allbooks.Add(bl);
        bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");
        allbooks.Add(bl);
        bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");
        allbooks.Add(bl);
        bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");
        allbooks.Add(bl);
        return allbooks;
    }
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lbllistbox.Text = this.ListBox1.SelectedValue;

    }
   
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
    }
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
    }
    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
    }

Notice the use of the Generic IList class template. An ArrayList class is used to pass the values. This kind of coding is alright when data is not strongly typed.
The rendered page looks like: 

Declarative Data Binding

ADO.Net uses two types of objects to access the data in a database. The dataset object contains one or more tables. The data provider objects include adapters, commands and connections.

The dataset stores the data retrieved from the database. The provider retrieves the data from the database using a command over a connection. The data adapter issues the Select statement which is stored in the command object and the command object uses the connection object to connect to the database and retrieve the data. The data adapter object is also capable of update the data in a database by issuing Insert, Delete, and Update statements. Once the data is retrieved the data provider disconnects from the database and the application works with the data saved in the dataset object. That is why; it is called to have disconnected data architecture.

Connecting with the database:

ADO.Net 2.0 has offered provider pattern, i.e. you choose the kind of database you are using to a single call to a provider factory. If you look in Machine.Config, you can see the providers for the following type of databases.

•Odbc Data Provider
•OleDb Data Provider
•OracleClient Data Provider
•SqlClient Data Provider
•SQL Server CE Data Provider

Once connected, you must send the commands to the database. This involves writing queries, updating existing data, inserting new data and deleting obsolete or wrong data.  Most databases support Structured Query Language (SQL) or its variation (like T-SQL) for writing these commands.

For example, say we have an SQL Database ‘Booklist’ with a ‘books’ table in it. To connect to that database and retrieve all the records from that table we will write code like:

Class myDBappl
 {
 static void Main(string[] args)
 {
 DbProviderFactory  providerfactory =  DbProviderFactories.GetFactory(“System.Data.SqlClient”);
 DbConnection conn = providerfactory.CreateConnection();
 using(conn)
{       ConfigurationSettings s = ConfigurationSettings.ConnectionStrings[“Booklist”];
 conn.ConnectionString = s.ConnectionString;
conn.Open();
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = “select * from books”;
DbDataReader reader = cmd.ExecuteReader();
//display the data .........
  }
 }
}

Working with the data:

Once you have connected to the database and retrieved the data, you need to use this data. ADO.Net provides for two different approaches to work with data.

•The IDataReader Interface, and
•The Dataset class.

DataReader:

We have already used the DbDataReader class in the previous code example.
DbDataReader reader = cmd.ExecuteReader();

The DbDataReader class uses the IDataReader Interface, using this you can retrieve one row at a time going forward only. So for more intense data related work where you need not only to display data, but select it , sort it, even page it you must use a dataset.

DataSet:

As we mentioned earlier ADO.Net uses disconnected data architecture, the DataSet class basically implements that. It retrieves a snapshot of data from the database and allows the user to work with it. It has two great advantages:

Firstly, it helps to overcome concurrency in the database. If more than one user tries to write on the same data simultaneously it leads to a concurrency problem. But using a dataset each user gets a copy of the required portion of the database as queried by the user. And secondly, it increases the scalability of the application, because here the connectivity with the database will not hinder the application’s progress, as each user will be disconnected after retrieving the required data.

DataSet class objects are built using a DataAdapter. A DataSet includes a DataTable array – one for each selection statement in the query. The DataSet contains a DataTable collection and creates a DataTable element for each select statement. The Tables collection could be accessed by either ordinal or String-type indices.

The following code shows an example of using the SqlDataAdapter to get a DataSet.

Public static void usedataset()
{
 DataSet ds = new DataSet();
 Try
 {
SqlDataAdapter da = new SqlDataAdapter( “select * from customer; select from country”,  “server=.; uid=sa; pwd=;database=CUSTOMERS”);
da.Fill(ds, “customer”);
 }catch(SqlException e)
{   System.Console.WriteLine(e);
}
 Foreach( DataTable t in ds.Tables)
  {
  Console.WriteLIne(“Table ” + t.TableName + “ is in the dataset” );
  Console.WriteLIne(“row 0 , column 1: “ + t.Rows[0][1]);
  Console.WriteLIne(“row 1 , column 1: “ + t.Rows[1][1]);
  Console.WriteLIne(“row 2 , column 1: “ + t.Rows[2][1]);
 }
 ds.WriteXml(“(c:\\dataset.xml”);
 ds.WriteXmlSchema(“(c:\\dataset.xsd”);
 ...
 ...
}

ASP.Net 2.0 fortunately provides much easier way to access data. The new classes it has included hide all complex coding for connection and data retrieving. Before finishing we will discuss use of one such Databound Control: the GridView. You can download the project files to observe use of other controls like: the FormView, DetailsView and DataList. The steps for using them are more or less similar.

The steps:

1.Create a web site. Add a new web form in it.
2.Pick up a GridView and drop it on the form.
3.Choose Data Source from the smart tag.
4.Enable Paging Sorting and Selection from the GridView configuration

After this configuration Visual Studio will show a representation of the table like this:

Use of other data controls are similar, Visual Studio gives AutoFormat option for other controls to customize the look of it.


 
Conclusion:

Working with databases and data-binding is much easier in ASP.Net 2.0 . You don’t have to write much code for simple jobs. But for customized works and better UI you still have to know the background story. It is vast, interesting and most often you end up loving it. So, start playing with data and data management. Believe me, this is what moving the earth these days.
Happy Programming!

About the Author:

NAME: PIYALI SENGUPTA

QUALIFICATION: B.E., M.C.A

AREA OF INTEREST: WEB PROGRAMMING

HOBBIES: READING AND TRAVELLING

I HAVE MOSTLY WORKED AS A FACULTY. PRESENTLY WORKING FROM HOME.I LOVE MATHEMATICS, ALGORITHMS, PROGRAMMING, FRIENDS, CHILDREN AND NATURE NOT NECESSARILY IN THIS ORDER.YOU CAN CONTACT ME AT: [email protected]