Data Binding in Asp.Net

Data Binding in Asp.Net

07 Jun 2024
Beginner
4.03K Views
10 min read

Data Binding in ASP.Net can be categorized into two: simple data binding and declarative data binding. Some controls support at least simple databinding while others support both. Simple databinding basically involves attaching any collection (item collection) that implements the IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control.

In this Asp.Net Tutorial, we will explore data binding in asp.net which will include what is data binding in asp. net, and types of data binding in asp.net.

What is data binding in ASP.NET?

Data binding is the process that establishes a connection between the app UI and the data it displays.

Types of data binding in asp.net.

  1. Simple data binding
  2. Declarative data binding

1.Simple Data Binding

We will discuss simple data binding with the help of a simple application. In this application, we have created a booklist class. This class has two string attributes a title (bookname) and author (authorname). On the page, we have used four data-bound 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 this:

Example:

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

2. 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 updating 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 a 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 types 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.

Example:

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 this:
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.
1.The IDataReader Interface
2. 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.

Example:


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 a 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 the 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 website. Add a new web form in it. 
2. Pick up a GridView and drop it on the form. 
3. Choose a 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:
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.  However, to simplify development and up your game, learn the intricacies of ASP.NET from ASP.NET Core Training Certification with ScholarHat by Dot Net Tricks and level up as an ASP.Net developer.

Take our Aspnet skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this