Resources » Code Snippets » ASP.NET WebForms

How to Edit / Delete records using Data List in ASP.NET?


Posted Date: 10-Jul-2011  Last Updated:   Category: ASP.NET WebForms    
Author: Member Level: Diamond    Points: 25


In this article I have explained about how to do edit /delete record details in data list control. For example I have display database record data in the data list control, now I want to edit some record details using data list like grid view control. This edit / delete operation is possible in Data List with help of Edit and Delete command in Data List. I have used that commands for this edit /delete operation.



Description
Normally we are use Grid view control for manipulate data in the ASP.NET. Similar to that Data List also perform Edit / Delete operations on data base records. In this example I have explained step by step about how to edit and delete record used Data List.

Client Side
I have placed one Data List control for display record details from database. In this client side code I have used two link buttons in the item template for show Edit and Delete buttons for each row in the data list control. In the EditItemTemplate used another two buttons for display Update and Cancel button, this buttons is only display when data list control in edit mode.

<%@ 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>DataList Edit/Delete</title>
<style type="text/css">
.btn
{
background-color: #033280;
color: White;
font-size: 12px;
font-weight: bold;
padding-left: 5px;
}
a
{
text-decoration: none;
font-weight: normal;
}
a:hover
{
text-decoration: underline;
}
.txt
{
font-size: 14px;
font-weight: bold;
padding-left: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="500" cellpadding="0" cellspacing="0" align="center">
<tr>
<td colspan="2" height="40">

</td>
</tr>
<tr>
<td colspan="2" height="40">
<b>DataList Edit/Delete Operations</b>
</td>
</tr>
<tr>
<td colspan="2" height="40">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2" bgcolor="#FBF4E0">
<asp:DataList ID="dlData" runat="server" OnEditCommand="dlData_EditCommand" DataKeyField="eno"
OnCancelCommand="dlData_CancelCommand" OnDeleteCommand="dlData_DeleteCommand"
OnUpdateCommand="dlData_UpdateCommand">
<HeaderTemplate>
<table width="600" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="30" class="btn">
Employee No.
</td>
<td class="btn">
Employee Name
</td>
<td class="btn">
Salary
</td>
<td colspan="2" class="btn" align="left">
Command
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td height="40" class="txt">
<%#Eval("eno") %>
</td>
<td class="txt">
<%#Eval("empname") %>
</td>
<td class="txt">
<%#Eval("sal") %>
</td>
<td class="txt">
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="edit" Text="Edit"></asp:LinkButton>
</td>
<td class="txt">
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="delete" Text="Delete"
OnClientClick="return confirm('Are you sure want delete this record?')"></asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td height="40" class="txt">
<%#Eval("eno") %>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("empname") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Employee Name cannot be blank!"
ControlToValidate="TextBox2" Display="None"></asp:RequiredFieldValidator>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server" Text='<%#Eval("sal") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Employee Salary cannot be blank!"
ControlToValidate="TextBox3" Display="None"></asp:RequiredFieldValidator>
</td>
<td class="txt">
<asp:LinkButton ID="lnkupdate" runat="server" CommandName="update" Text="Update"></asp:LinkButton>
</td>
<td class="txt">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="cancel" Text="Cancel"
CausesValidation="false"></asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Data List Properties

HeaderTemplate: It is used to set header text for data list control.

ItemTemplate: It is used to bind your database records into the DataList control.

FooterTemplate: It is used to set some footer text on your Data List control.

Server Side:
In the server side we have do the edit /delete operations based on the user selection.

First bind data from database into the DataList control when page load first time.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind data to the Data List control when page load first time
bindList();
}
}
void bindList()
{
//Open Sql server Connection
sqlcon.Open();
sqlcmd = new SqlCommand("select * from emp", sqlcon);
//Execute query and fill value in data table
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
if(dt.Rows.Count>0)
{
//Bind data into the DataList control
dlData.DataSource = dt;
dlData.DataBind();
}
//Close SQl Server Connection
sqlcon.Close();
}

Image1

Now user click the Edit button for modify details in the data list control.

protected void dlData_EditCommand(object source, DataListCommandEventArgs e)
{
//Get Edit Item index when user click edit button
dlData.EditItemIndex = e.Item.ItemIndex;
bindList();
}

image2

Validate the user input during modify data in the data list control using ASP.NET validation controls like this

Image3

After user entered all details in the data list control, click the update button for update data

image4


protected void dlData_UpdateCommand(object source, DataListCommandEventArgs e)
{
//Get User entered value in the Edit mode text boxes
string empname=((TextBox)e.Item.FindControl("TextBox2")).Text;
string sal=((TextBox)e.Item.FindControl("TextBox3")).Text;

//Get the Identity Primary DataKey value when user click update button
int eno = Convert.ToInt32(dlData.DataKeys[e.Item.ItemIndex]);
sqlcmd = new SqlCommand("update emp set empname='" + empname + "',sal='" + sal + "' where eno='" + eno +"'",sqlcon);
sqlcon.Open();
//Execute query to perform update operation on SQL Server
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Set datalist default index -1 for display record
dlData.EditItemIndex = -1;
//Bind new updated data on DataList control
bindList();
}

image5

If user click cancel button then leave it data as it is before.

//Cancel operation execute when user click cancel button during update
protected void dlData_CancelCommand(object source, DataListCommandEventArgs e)
{
//Leave it Item in default for reload DataList
dlData.EditItemIndex = -1;
bindList();
}

If user click the delete button show confirm message if user click yes in that confirm message then delete that record from database

image6


protected void dlData_DeleteCommand(object source, DataListCommandEventArgs e)
{
//Get the Identity Primary DataKey value when user click delete button
int eno = Convert.ToInt32(dlData.DataKeys[e.Item.ItemIndex]);
sqlcmd = new SqlCommand("delete from emp where eno='" + eno +"'",sqlcon);
sqlcon.Open();
//Execute query to perform delete operation on SQL Server
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
//Bind new updated data on DataList control
bindList();
}

Result Data
image7

Source code:
Download the attached source code and try to edit / delete record from database using Data List.
Front End: ASP.NET
Code Behind: C#

Conclusion:
I hope this article is help to know about Data List Edit / Delete operations in ASP.NET.


Did you like this resource? Share it with your friends and show your love!

Responses to "How to Edit / Delete records using Data List in ASP.NET?"
Author: Suresh Sellathambi    14 Jul 2011Member Level: Gold   Points : 1
Hi Ravi,

Really good Articles. Thank you for this clear tutorial, it is most useful.

Keep it. Now I am Clear in DataList.

Thanks

S.Suresh



Guest Author: zaid khan     24 Feb 2013
can u please tell me how to sum columns values on footer .like grand total of records of all column in datalist


Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Laxmikant
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India