How to Insert ,Edit ,Update,Delete,Cancel and Print records in Data List control in asp.net

By

Data List control is used to display the entire table data like Gridview and Repeater control in asp.net.It is a Web Form control which is used in asp.net
There are some points about Data List Control:-
  • Data List control has not a default layout like Gridview control in asp.net. 
  • Data List control is converted to Html table tag on Browser side like Gridview in asp.net.
  • Data List control has predefined event to add,delete,Edit,update and cancel the record.
Now i am going to make an application ,which can perform many operations.You can use this application for any organization,institute or other places by customizing it.
There are some operations which are performed in this application which are given below:-
  • Insert Data in Data List control 
  • Edit specific Data in Data List control
  • Update specific Data in Data List control
  • Cancel Data in Data List control
  • Delete Data in Data List control
  • Take Print out of Data in Data List control   
In our previous tutorials i had made two application which can be used in any organizations. which are given below:-
 There are some steps to make this application which are given below:-
Step 1:- First open your visual studio --> File-->New-->Website-->Select ASP.NET Empty website --> OK -->Open solution Explorer --> Add a Web Form (Default.aspx).

Step 2:-  Now Add Database.mdf file in your website -->Create a employee table with three column as shown below:
employee table

Note:-You can create table separately in database(Sql ,MySQL etc.) and connect to this application .If you are facing any problem to add .mdf file on website then visit below links :-
  1. How add .mdf file on asp.net website.
  2. How to solve sql server problems.
 Step 3:- Now open your Default.aspx page -->Click Source button from below-->Write the following Data List layout code(html code) as given below:-
<%@ 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>
<head>
<title></title>
    <style type="text/css">
        #form1
        {
            width: 1168px;
        }
    </style>
</head>
<form id="form1" runat="server">
<body style="width: 970px; height: 341px">
    <asp:Label ID="Label4" runat="server" Text="*" style="color: #990000"></asp:Label>
    <br />
    <asp:LinkButton ID="LinkButton5" runat="server" onclick="LinkButton5_Click" 
        style="font-weight: 700; font-size: large">Take Preview</asp:LinkButton>
<asp:DataList id="DataList1" runat="server" Width="825px" Height="327px" 
        oncancelcommand="DataList1_CancelCommand" 
        oneditcommand="DataList1_EditCommand" ondeletecommand="DataList1_DeleteCommand" 
        onupdatecommand="DataList1_UpdateCommand" 
        onitemcommand="DataList1_ItemCommand" style="margin-top: 10px">
<HeaderTemplate>
<table border="0" width="100%" >
<tr>
<td><b>Emp Id</b></td>
<td><b>Emp Name</b></td>
<td><b>Salary</b></td>
<td><b>Make Change</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label ID="Label1" runat="server" Text='<%#Eval("eid")%>'/></td>
<td><asp:Label ID="Label2" runat="server" Text='<%#Eval("name")%>'/></td>
<td><asp:Label ID="Label5" runat="server" Text='<%#Eval("salary")%>'/></td>
<td>
<asp:LinkButton ID="LinkButton1" CommandName="edit" style="color: #0000FF;font-size: large" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" CommandName="delete" style="color: #0000FF;font-size: large" runat="server">Delete</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td><asp:Label ID="Label5" runat="server" Text="Label"></asp:Label></td>
<td><asp:TextBox ID="TextBox4" runat="Server"></asp:TextBox></td>
<td><asp:TextBox ID="TextBox5" runat="Server"></asp:TextBox></td>
<td><asp:LinkButton ID="LinkButton3" CommandName="Insert" style="color: #0000FF;font-size: large" runat="server">Insert</asp:LinkButton></td>
</tr>
</table>
</FooterTemplate>
<EditItemTemplate>
<tr>
<td><asp:Label ID="Label3" runat="server" Text='<%#Eval("eid")%>'/></td>
<td><asp:TextBox ID="TextBox1" runat="Server" Text='<%#Eval("name")%>'></asp:TextBox></td>
<td><asp:TextBox ID="TextBox3" runat="Server" Text='<%#Eval("salary")%>'></asp:TextBox></td>
<td>
<asp:LinkButton ID="LinkButton3" CommandName="update" style="color: #990000;font-size: large" runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" CommandName="cancel" style="color: #990000;font-size: large" runat="server">Cancel</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
</asp:DataList>  
</form>
</body>
</html>
 
  Step 4:- Now click Design from the below of  Default.aspx page-->you will see following layout of Data List control as shown below:-
layout

 Note:- I have given full explanation of the layout code in  Repeater control application

Step 5:-  Now go properties of Data List control-->Click Events--> Now generate handler by double click on each as shown below:- 

Step 6:- Now Open Default.aspx.cs page (or press F7 --> and Write the following c# codes as given below:- 
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            GetData();
        }
    }
    private void GetData()
    {
 SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");

        try
        {

            con.Open();
            SqlCommand cmd = new SqlCommand("select * from employee", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataList1.DataSource = ds.Tables[0];
            DataList1.DataBind();
        }
        finally
        {
            con.Close();
        }
    }
  protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
    {
        DataList1.EditItemIndex = e.Item.ItemIndex;
        GetData();
    }
 protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
    {
        DataList1.EditItemIndex = -1;
        GetData();
    }
    protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
    {
        String eid = ((Label)e.Item.FindControl("Label3")).Text;
        TextBox name = (TextBox)e.Item.FindControl("TextBox1");
        TextBox salary = (TextBox)e.Item.FindControl("TextBox3");
   SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
        con.Open();
        SqlCommand cmd = new SqlCommand("update employee set name='" + name.Text + "',salary='" + salary.Text + "'where eid ='" + eid + "'", con);
        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            Label4.Text = "Recard Updated successfully....";
            GetData();
        }
    }
    protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        String eid = ((Label)e.Item.FindControl("Label1")).Text;
 SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;");
        con.Open();
        SqlCommand cmd = new SqlCommand("delete from employee where eid='" + eid + "'", con);
        int i = cmd.ExecuteNonQuery();
        if (i > 0)
        {
            Label4.Text = "Recard Deleted successfully....";
            GetData();
        }
    }
    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
 SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");
            con.Open();
            TextBox ename = (TextBox)e.Item.FindControl("TextBox4");
            TextBox salary = (TextBox)e.Item.FindControl("TextBox5");
            SqlCommand cmd = new SqlCommand("insert into employee values('" + ename.Text + "','" + salary.Text + "')", con);
            int i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                Label4.Text = "Recard inserted successfully....";
                GetData();
            }
        }
    }
    protected void LinkButton5_Click(object sender, EventArgs e)
    {
        Response.Redirect("default2.aspx");
    }
}

Step 7 :- Now Add another web Form (Default2.aspx)-->click Source button -->and write Data List layout (Html)codes and java script codes as given below:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<title></title>
    <style type="text/css">
        #form1
        {
            width: 1168px;
        }
    </style>
    <script type="text/javascript">
        function print_page() {
            window.print();
        } 
    </script> 
</head>
<div>
<a href="#" onclick="javascript :print_page();"><strong><span class="style1">Take print out</span></strong></a>
</div>
<form>
<body>
    <asp:Label ID="Label4" runat="server" Text="*" style="color: #990000"></asp:Label>
    <br />
<asp:DataList id="DataList1" runat="server" Width="825px" Height="327px">
<HeaderTemplate>
<table border="0" width="100%" >
<tr>
<td><b>Emp Id</b></td>
<td><b>Emp Name</b></td>
<td><b>Salary</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label ID="Label1" runat="server" Text='<%#Eval("eid")%>'/></td>
<td><asp:Label ID="Label2" runat="server" Text='<%#Eval("name")%>'/></td>
<td><asp:Label ID="Label5" runat="server" Text='<%#Eval("salary")%>'/></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
<EditItemTemplate>
</EditItemTemplate>
</asp:DataList>  
</form>
</body>
</html>

Description:- In above codes i have explained how to take preview of Data List data and print it.In above codes i have written script code  in <head> section for printing the Data List data as given below:-
<head>
<title></title>
    <script type="text/javascript">
        function print_page() {
            window.print();
        } 
    </script> 
</head>
Now i have called this script function(print_page()) from <div> section on Button click as given below:-
</head>
<div>
<a href="#" onclick="javascript :print_page();"><strong><span class="style1">Take print out</span></strong></a>
</div>
<form>

Step 8 :- Now click design --> You will see following layout as shown below:-

layout_2

Step 9:- Now open default.aspx.cs page(or press F7) --> and Write the following c# codes as given below:-
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            GetData();
        }
    }

    private void GetData()
    {
 SqlConnection con = new SqlConnection(@"Data Source=.;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True;Max Pool Size=20; Connection Timeout=10;");

        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from employee", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataList1.DataSource = ds.Tables[0];
            DataList1.DataBind();
        }
        finally
        {
            con.Close();
        }
    }
}

Step 10:- Now Run the Application (press F5)-->Follow some points which are given below:-
  • Write the Name and Salary fields values in below Text Box as shown below--> and  Press Insert button.
insert


  • Now Click Edit Button Emp Id (eid)=103 as shown below:-
Edit


  • Now Change the  Emp Name value from  mohan to Manmohan singh and salary value 40000 to 4500. -->click Update button as shown below:-
Update
  • Now click Cancel Button for changing the Edit mode properties as shown below:-
cancel

  • Now Delete Emp Id = 105 as show below:-

Delete
  • Now click Take Preview Button -->You will see following preview as shown below:-
preview

  • Now Click Take print out button -->You can take print out of the Existing page or save in pdf file (save --> save as pdf -->save) as shown below:-


print



I hope this is Helpful for you.
For More....

  1. How to send forget password code from asp.net website free
  2. Create Generic Handler application is asp.net
  3. Views is Microsoft sql server
  4. Create captcha image without dll file
  5. Send Mail from asp.net application free
  6. Create setup file with database in windows form application
  7. Generic collections in c#
  8. Generate unique Number and stored in database
  9. Create dll file and use .NET Applications
  10. How to create Data set and Data Adapter in ADO.NET

To Get the Latest  Free Updates Subscribe
Click below link for download whole Application
                Download

5 comments:

  1. Gving error in this line-> string id = ((Label)GridView1.FindControl("lbl_id")).Text;
    Error: object reference is not set to an instance of an object.
    After changing some conversion method giving error on the line
    SqlCommand cmd = new SqlCommand("update tbl_reg set user_name='" + unm.Text + "',password='" + pass.Text + "', mobile='" + mob.Text + "',email='" + email.Text + "' where id='" + id + "'", con)
    Here is same message:object reference is not set to an instance of an object.

    ReplyDelete
    Replies
    1. your "lbl_id" in not correct.Means use Edititem template Label.go step 3 i have used Label 3 which used in EditItem Template Field.you also use like this.if any problem ask again..........

      Delete
  2. How to Create a Login Page with Database

    ReplyDelete
  3. Hi Kuldeep ! Read Below link
    http://www.msdotnet.co.in/2013/04/how-to-make-registration-and-login-form.html

    ReplyDelete
  4. hi, can u help me with an application for windows which is used by a shopkeeper to maintain his stock

    ReplyDelete

Powered by Blogger.