How to Bind and Perform Update, Edit, Delete Operation on DataList Control in 3 Tier in ASP.Net

This article shows how to bind and perform edit, update, and delete operations on a Datalist Control in 3 tiers in ASP.NET using C#.

Initial chamber

Step 1. Open Visual Studio 2010 and create an Empty Website, giving it a suitable name (DataList_demo).

Step 2. In Solution Explorer, you will get your empty website. Add a web form, SQL Database, and 3 class files as in the following.

For web form

DataList_demo (your empty website), right-click and Add New Item, Web Form. Name it datalist_demo.aspx.

For SQL Server Database

DataList_demo (your empty website), right-click and Add New Item, SQL Server Database (Add the database inside the App_Data_folder).

For 3 Class Files

DataList_demo (your empty website), right-click and Add New Item, Class (add 3 class files, add your class file in the App_code folder), they provide the names as:

  1. Common functions.cs
  2. BAL_user_operation.cs
  3. DAL_user_operation.cs

Database chamber

Step 3. In Server Explorer, click on your database (Database.mdf), Tables, and Add New Table. Make the table as in the following:

  • Table, tbl_data (Don't Forget to make ID as IS Identity -- True).
    ID
  • Add a Stored Procedure to edit, update, insert, and delete data by going to the database (Database.mdf), Store Procedures, and right-click, then add some new Stored Procedures as in the following.
  • sp_getdata()
    Alter procedure
  • sp_insert()
    Insert
  • sp_update()
    Update
  • sp_delete()
    delete
  • These are all the Stored Procedures that we will use for updating, deleting, and editing our data in the DataList.

Design code

Step 4. It's time for the serious design in the DataList. Let's begin by opening your Datalist.aspx page and try the code as in the following.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 75px;
        }
        .style3
        {
            width: 82px;
        }
        .style4
        {
            width: 234px;
        }
        .style5
        {
            width: 19px;
        }
        .style6
        {
            text-decoration: underline;
            font-size: large;
            color: #3333CC;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    <table style="width:100%;">
        <caption class="style6">
            <strong>DataList Control in Asp.Net</strong></caption>
        <tr>
            <td>
                 </td>
            <td>
                 </td>
            <td>
                 </td>
        </tr>
        <tr>
            <td>
                 </td>
            <td>
                 </td>
            <td>
                 </td>
        </tr>
        <tr>
            <td>
                 </td>
            <td>
    <asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84"    
        BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"    
        CellSpacing="2" DataKeyField="id" GridLines="Both"    
        oncancelcommand="DataList1_CancelCommand"    
        ondeletecommand="DataList1_DeleteCommand" oneditcommand="DataList1_EditCommand"    
        onupdatecommand="DataList1_UpdateCommand" RepeatDirection="Horizontal">
        <EditItemTemplate>
            <table style="width:100%;">
                <tr>
                    <td class="style1">
                          </td>
                    <td class="style3">
                          </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                          </td>
                    <td class="style3">
                          </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                        Name:</td>
                    <td class="style3">
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                        Email:</td>
                    <td class="style3">
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("email") %>'></asp:TextBox>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                        Designation:</td>
                    <td class="style3">
                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("designation") %>'></asp:TextBox>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                        City:</td>
                    <td class="style3">
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                          </td>
                    <td class="style3">
                          </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style1">
                        <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>
                    </td>
                    <td class="style3">
                        <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                    </td>
                    <td>
                          </td>
                </tr>
            </table>
        </EditItemTemplate>
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
        <ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        <ItemTemplate>
            <table style="width:100%;">
                <tr>
                    <td class="style4">
                          </td>
                    <td class="style5">
                          </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                        <asp:Image ID="Image1" runat="server" BackColor="#FF99FF" BorderColor="#993399"    
                            Height="191px" ImageAlign="AbsBottom" ImageUrl='<%# Bind("pic") %>'    
                            Width="199px" />
                    </td>
                </tr>
                <tr>
                    <td class="style4">
                        Name:</td>
                    <td class="style5">
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                        Email:</td>
                    <td class="style5">
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("email") %>'></asp:Label>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                        Designation</td>
                    <td class="style5">
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("designation") %>'></asp:Label>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                        City:</td>
                    <td class="style5">
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("city") %>'></asp:Label>
                    </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                          </td>
                    <td class="style5">
                          </td>
                    <td>
                          </td>
                </tr>
                <tr>
                    <td class="style4">
                        <asp:LinkButton ID="LinkButton3" CommandName="Edit" runat="server">Edit</asp:LinkButton>
                    </td>
                    <td class="style5">
                        <asp:LinkButton ID="LinkButton4"  CommandName="Delete" runat="server">Delete</asp:LinkButton>
                    </td>
                    <td>
                          </td>
                </tr>
            </table>
        </ItemTemplate>
        <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
    </asp:DataList>
            </td>
           
        </tr>
    </table>
    </form>
</body>
</html>

Or you can do it manually like this.

  1. Drag your Datalist from the toolbox to the design page.
  2. Click on the arrow sign of the Datalist; you will enter into the Edit Template.
  3. Now in the DataList Task, there is a dropdown. From there, select Item Template.
  4. In the Item Template, drag an HTML table.
  5. Inside the table, drag an Image Control, 4 labels, and 2 Hyperlinks.
  6. Design like the following.
    Item template

Now you need to click the arrow sign of the Image Control and click on Edit DataBindings.

DataBindings

Here click on the ImageUrl and bind your Image URL by giving Bind(“pic”) in the code expression as in the preceding figure. In the same way, we can do it for all the labels.

  1. Label Name
    Label name
  2. Label Email
    Label email
  3. Label Designation
    Label designation
  4. Label City
    Label city

Now return to the Edit template of the Datalist select Edit Item Template and make the design like the following.

Edit template

For binding to the TextBox I will show you the binding for Textbox1 (TextBox for Name:).

bind

Similarly do it for all the textboxes (email, designation, and city).

Code chamber

  1. Open the Commonfunction.cs file and add the following code.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Configuration;
    /// <summary>
    /// Summary description for Commonfunctions
    /// </summary>
    public class Commonfunctions
    {
        public Commonfunctions()
        {
            // 
            // TODO: Add constructor logic here
            // 
        }
        public static string getconstring()
        {
            return ConfigurationManager.ConnectionStrings["dbcon"].ToString();
        }
    }
    
    The preceding code is written for a SQL Connection String that we need to call again and again by going to the database property. This is a lengthy process, that's why we made this class and now we will just call its method getconstring() which makes our process shorter and easier.
  2. Open the DAL_user_operation.cs file and code it like the following.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Data.SqlClient;
    /// <summary>
    /// Summary description for DAL_user_operation
    /// </summary>
    public class DAL_user_operation
    {
        public DAL_user_operation()
        {
            // 
            // TODO: Add constructor logic here
            // 
        }
        // Inserting Code
        public bool user_insert(string name, string email, string designation, string city, string pic)
        {
            SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
            SqlCommand cmd = new SqlCommand("sp_insert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("name", name);
            cmd.Parameters.AddWithValue("email", email);
            cmd.Parameters.AddWithValue("designation", designation);
            cmd.Parameters.AddWithValue("city", city);
            cmd.Parameters.AddWithValue("pic", pic);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            if (i != 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        // Delete Code
        public void user_delete(int id)
        {
            SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
            SqlCommand cmd = new SqlCommand("sp_delete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("id", id);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
        }
        // Update Code
        public void user_update(string name, string email, string designation, string city, int id)
        {
            SqlConnection con = new SqlConnection(Commonfunctions.getconstring());
            SqlCommand cmd = new SqlCommand("sp_update", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("name", name);
            cmd.Parameters.AddWithValue("email", email);
            cmd.Parameters.AddWithValue("designation", designation);
            cmd.Parameters.AddWithValue("city", city);
            cmd.Parameters.AddWithValue("id", id);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();   
        }
        public DataTable getdata()
        {
            SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("sp_getdata", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            return dt;
        }
    }
  3. Open your BAL_user_operation.cs file and code it like the following.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Data.SqlClient;
    /// <summary>
    /// Summary description for BAL_user_operation
    /// </summary>
    public class BAL_user_operation
    {
        DAL_user_operation du = new DAL_user_operation();
        public BAL_user_operation()
        {
            // 
            // TODO: Add constructor logic here
            // 
        }
        public bool user_insert(string name, string email, string designation, string city, string pic)
        {
           return du.user_insert(name, email, designation, city, pic);     
        }
        public void user_delete(int id)
        {
            du.user_delete(id);
        }
        public void user_update(string name, string email, string designation,  string city, int id)
        {
            du.user_update(name, email, designation, city, id);   
        }
        public DataTable getdata()
        {
            return du.getdata();
        }
    }
  4. Finally, open the DataList.aspx.cs file and code it like the following.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    public partial class _Default : System.Web.UI.Page
    {
        BAL_user_operation bu = new BAL_user_operation();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                refreshdata();
            }
    
        }
        public void refreshdata()
        {
            DataList1.DataSource = bu.getdata();
            DataList1.DataBind();
        }
        protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
        {
            DataList1.EditItemIndex = -1;
            refreshdata();
        }
        protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            int id = Convert.ToInt16(DataList1.DataKeys[e.Item.ItemIndex].ToString());
            bu.user_delete(id);
            refreshdata();
        }
        protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
        {
            DataList1.EditItemIndex = e.Item.ItemIndex;
            refreshdata();
        }
        protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            TextBox txtname = DataList1.Items[e.Item.ItemIndex].FindControl("TextBox1") as TextBox;
            TextBox txtemail = DataList1.Items[e.Item.ItemIndex].FindControl("TextBox3") as TextBox;
            TextBox txtdesignation = DataList1.Items[e.Item.ItemIndex].FindControl("TextBox4") as TextBox;
            TextBox txtcity = DataList1.Items[e.Item.ItemIndex].FindControl("TextBox2") as TextBox;
            int id = int.Parse(DataList1.DataKeys[e.Item.ItemIndex].ToString());
            bu.user_update(txtname.Text, txtemail.Text, txtdesignation.Text, txtcity.Text, id);
            DataList1.EditItemIndex = -1;
            refreshdata();
        }
    }
    This is your web.config file code.
    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <connectionStrings>
        <add name="dbcon" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
      </connectionStrings>
    </configuration>
    

Output chamber

Output Chamber

data list control

I hope you will like this. Thank you for reading.

Have a nice day.


Similar Articles