(Add edit delete update records in Datalist) – Đối với những bảng dữ liệu có ít cột, người lập trình có thể xây dựng chức năng: Thêm, sửa dữ liệu ngay tại Datalist. Khi xây dựng các chức năng .Với cách xây dựng này sẽ giúp người sử dụng dễ dàng và nhanh chóng hơn khi cần thêm, sửa dữ liệu. Bài viết dưới đây sẽ hướng dẫn các bạn thực hiện công việc này.
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Accounts có cấu trúc phía dưới- B1: Tạo CSDL Customers trong SQL Server
- B3: Nhập dữ liệu cho bảng Accounts
- B4: Tạo các stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Accounts_Add]
@AccountCode nvarchar(25)
,@AccName nvarchar(250)
,@AccAddress nvarchar(250)
,@AccPhone nvarchar(80)
,@AccFAX nvarchar(50)
,@AccEmail nvarchar(500)
,@AccWebsite nvarchar(150)
,@AccDesc nvarchar(2000)
AS
INSERT INTO Accounts (
[AccountCode]
,[AccName]
,[AccAddress]
,[AccPhone]
,[AccFAX]
,[AccEmail]
,[AccWebsite]
,[AccDesc]
,[CreatedDate]
,[ModifiedDate]
) VALUES (
@AccountCode
,@AccName
,@AccAddress
,@AccPhone
,@AccFAX
,@AccEmail
,@AccWebsite
,@AccDesc
,getdate()
,getdate()
)
select SCOPE_IDENTITY()
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_Update]
@AccountID int,
@AccountCode nvarchar(25),
@AccName nvarchar(250),
@AccAddress nvarchar(250),
@AccPhone nvarchar(80),
@AccFAX nvarchar(50),
@AccEmail nvarchar(500),
@AccWebsite nvarchar(150),
@AccDesc nvarchar(2000)
AS
UPDATE Accounts SET
[AccountCode] = @AccountCode
,[AccName] = @AccName
,[AccAddress] = @AccAddress
,[AccPhone] = @AccPhone
,[AccFAX] = @AccFAX
,[AccEmail] = @AccEmail
,[AccWebsite] = @AccWebsite
,[AccDesc] = @AccDesc
,[ModifiedDate] = getdate()
WHERE
[AccountID] = @AccountID
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_List]
@Keyword nvarchar(250),
@SortField nvarchar(50),
@SortType nvarchar(10)
AS
declare @strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Accounts'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (AccountCode like N''%' +@Keyword+'%''
Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'
if @SortField='CreatedDate'
Begin
set @strOrder =' Order by CreatedDate'
End
Else
Begin
set @strOrder =' Order by AccName'
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
GO
CREATE PROCEDURE [dbo].[Pro_Accounts_Delete]
@ItemID int
AS
DELETE FROM Accounts
WHERE AccountID = @ItemID
Go
- B5: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
Imports System.Data.SqlClient
Imports System.Data
Namespace InsertUpdateDeleteRecords
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString As String
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function FillTable(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
Try
Dim tb As New DataTable
Dim adap As New SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If Not Para Is Nothing Then
For Each p As ObjectPara In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
End If
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function RunSQL(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As Integer
Dim iExecute As Integer = 0
Try
Dim _cnn As New SqlConnection(_connectionString)
_cnn.Open()
Dim cmd As New SqlCommand(ProcName, _cnn)
cmd.CommandType = CommandType.StoredProcedure
For Each p As ObjectPara In Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
'cmd.ExecuteScalar()
iExecute = cmd.ExecuteNonQuery()
Catch ex As Exception
End Try
Return iExecute
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Value() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B6: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C# Code
<%@ PageTitle="How to add edit delete update records in Datalist ASP.NET" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="Insert_Update_DeleteRecordsInDatalist._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
</asp:ScriptManager>
<h3>
How to add edit delete update records in Datalist ASP.NET
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
</td>
<tdalign="right">
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</td>
</tr>
<trid="trMessage"runat="server"visible="false">
<td colspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<tdcolspan="2">
<asp:DataList ID="dlObject" runat="server" DataKeyField="AccountID" Width="100%"
OnEditCommand="dlObject_EditCommand"
OnItemCommand="dlObject_ItemCommand"
OnUpdateCommand="dlObject_UpdateCommand"
OnItemDataBound="dlObject_ItemDataBound"
OnDeleteCommand="dlObject_DeleteCommand"
OnCancelCommand="dlObject_CancelCommand">
<HeaderStyle CssClass="GridStyle_HeaderStyle" />
<ItemStyle CssClass="GridStyle_RowStyle"/>
<HeaderTemplate>
<table cellpadding="0"cellspacing="0"width="100%">
<tr>
<th align="center"width="80px">AccountCode</th>
<th align="center"width="160px">AccountName</th>
<th align="center"width="100px">Phone</th>
<th align="center"width="100px">Fax</th>
<th align="center"width="120px">Email</th>
<th align="center"width="100px">Website</th>
<th align="center"width="50px"></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="80px">
<asp:Label ID="lblAccountID"runat="server"Visible="false"Text='<%# Eval("AccountID") %>' />
<asp:Label ID="lblAccountCode"runat="server"Text='<%# Eval("AccountCode") %>' />
</td>
<td align="left"width="160px">
<asp:Label ID="lblAccName" runat="server" Text='<%# Eval("AccName") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblPhone"runat="server"Text='<%# Eval("AccPhone") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblAccFAX"runat="server"Text='<%# Eval("AccFAX") %>' />
</td>
<td align="left"width="120px">
<asp:Label ID="lblEmail"runat="server"Text='<%# Eval("AccEmail") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblWebsite"runat="server"Text='<%# Eval("AccWebsite") %>' />
</td>
<td align="center"width="50px">
<asp:ImageButton ID="cmdEdit"CommandName="Edit"runat="server"ImageUrl="~/images/edit.gif"CausesValidation="False"></asp:ImageButton>
<asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td width="80px">
<asp:Label ID="lblAccountID_Edit"runat="server"Visible="false"Text='<%# Eval("AccountID") %>' />
<asp:TextBox ID="txtAccountCode"CssClass="form-control"Width="100px"runat="server"Text='<%# Bind("AccountCode") %>' />
</td>
<td width="160px">
<asp:TextBox ID="txtAccountName"CssClass="form-control"runat="server"Width="150px"Text='<%# Bind("AccName") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtPhone"CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccPhone") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtFAX" CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccFAX") %>' />
</td>
<td width="120px">
<asp:TextBox ID="txtEmail"CssClass="form-control"runat="server"Width="120px"Text='<%# Bind("AccEmail") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtWebsite"CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccWebsite") %>' />
</td>
<td width="50px">
<asp:ImageButton ID="cmdUpdate"CommandName="Update"ToolTip="Update Account" runat="server" ImageUrl="~/images/save.gif"></asp:ImageButton>
<asp:ImageButton ID="cmdCancel"CommandName="Cancel"runat="server"ImageUrl="~/images/cancel.gif"></asp:ImageButton>
</td>
</tr>
</EditItemTemplate>
<FooterTemplate>
<tr>
<td width="80px">
<asp:TextBox ID="txtAccountCode_Footer" CssClass="form-control"runat="server"Width="80px"/>
<asp:RequiredFieldValidatorID="valAccountCode"runat="server"ValidationGroup="Footer"ControlToValidate="txtAccountCode_Footer"Display="dynamic"ErrorMessage="Enter Account Code"></asp:RequiredFieldValidator>
</td>
<td width="160px">
<asp:TextBox ID="txtAccName_Footer"CssClass="form-control"runat="server"Width="150px"/>
<asp:RequiredFieldValidatorID="valAccountName"runat="server"ValidationGroup="Footer"ControlToValidate="txtAccName_Footer"Display="dynamic"ErrorMessage="Enter Account Name"></asp:RequiredFieldValidator>
</td>
<td width="100px">
<asp:TextBox ID="txtPhone_Footer"CssClass="form-control"runat="server"Width="100px"/>
</td>
<td width="100px">
<asp:TextBox ID="txtFax_Footer"CssClass="form-control"runat="server"Width="100px"/>
</td>
<td width="120px">
<asp:TextBox ID="txtEmail_Footer"CssClass="form-control"runat="server"Width="120px"/>
</td>
<td width="100px">
<asp:TextBox ID="txtWebsite_Footer"CssClass="form-control"runat="server"Width="120px"/>
</td>
<td width="50px">
<asp:ImageButton ID="cmdInsert"CommandName="Add"ValidationGroup="Footer"ToolTip="Add Account" runat="server" ImageUrl="~/images/add.gif"></asp:ImageButton>
</td>
</tr>
</table>
</FooterTemplate>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>VB.NET Code
<%@ PageTitle="How to add edit delete update records in Datalist ASP.NET" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"EnableEventValidation="false" CodeBehind="Default.aspx.vb" Inherits="Insert_Update_DeleteRecordsInDatalist._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
</asp:ScriptManager>
<h3>
How to add edit delete update records in Datalist ASP.NET
</h3>
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"cellspacing="3"width="100%">
<tr>
<td>
</td>
<tdalign="right">
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</td>
</tr>
<trid="trMessage"runat="server"visible="false">
<tdcolspan="2">
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<tdcolspan="2">
<asp:DataList ID="dlObject" runat="server" DataKeyField="AccountID" Width="100%">
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<ItemStyle CssClass="GridStyle_RowStyle"/>
<HeaderTemplate>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<th align="center"width="80px">AccountCode</th>
<th align="center"width="160px">AccountName</th>
<th align="center"width="100px">Phone</th>
<th align="center"width="100px">Fax</th>
<th align="center"width="120px">Email</th>
<th align="center"width="100px">Website</th>
<th align="center"width="50px"></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="80px">
<asp:Label ID="lblAccountID"runat="server"Visible="false"Text='<%# Eval("AccountID") %>' />
<asp:Label ID="lblAccountCode"runat="server"Text='<%# Eval("AccountCode") %>' />
</td>
<td align="left"width="160px">
<asp:Label ID="lblAccName"runat="server"Text='<%# Eval("AccName") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblPhone"runat="server"Text='<%# Eval("AccPhone") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblAccFAX"runat="server"Text='<%# Eval("AccFAX") %>' />
</td>
<td align="left" width="120px">
<asp:Label ID="lblEmail"runat="server"Text='<%# Eval("AccEmail") %>' />
</td>
<td align="left"width="100px">
<asp:Label ID="lblWebsite"runat="server"Text='<%# Eval("AccWebsite") %>' />
</td>
<td align="center"width="50px">
<asp:ImageButton ID="cmdEdit"CommandName="Edit"runat="server"ImageUrl="~/images/edit.gif"CausesValidation="False"></asp:ImageButton>
<asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td width="80px">
<asp:Label ID="lblAccountID_Edit"runat="server"Visible="false"Text='<%# Eval("AccountID") %>' />
<asp:TextBox ID="txtAccountCode"CssClass="form-control"Width="100px"runat="server"Text='<%# Bind("AccountCode") %>' />
</td>
<td width="160px">
<asp:TextBox ID="txtAccountName"CssClass="form-control"runat="server"Width="150px"Text='<%# Bind("AccName") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtPhone"CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccPhone") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtFAX" CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccFAX") %>' />
</td>
<td width="120px">
<asp:TextBox ID="txtEmail"CssClass="form-control"runat="server"Width="120px"Text='<%# Bind("AccEmail") %>' />
</td>
<td width="100px">
<asp:TextBox ID="txtWebsite"CssClass="form-control"runat="server"Width="100px"Text='<%# Bind("AccWebsite") %>' />
</td>
<td width="50px">
<asp:ImageButton ID="cmdUpdate"CommandName="Update"ToolTip="Update Account" runat="server" ImageUrl="~/images/save.gif"></asp:ImageButton>
<asp:ImageButton ID="cmdCancel"CommandName="Cancel"runat="server"ImageUrl="~/images/cancel.gif"></asp:ImageButton>
</td>
</tr>
</EditItemTemplate>
<FooterTemplate>
<tr>
<td width="80px">
<asp:TextBox ID="txtAccountCode_Footer"CssClass="form-control"runat="server"Width="80px"/>
<asp:RequiredFieldValidatorID="valAccountCode"runat="server"ValidationGroup="Footer"ControlToValidate="txtAccountCode_Footer"Display="dynamic"ErrorMessage="Enter Account Code"></asp:RequiredFieldValidator>
</td>
<td width="160px">
<asp:TextBox ID="txtAccName_Footer"CssClass="form-control"runat="server"Width="150px"/>
<asp:RequiredFieldValidatorID="valAccountName"runat="server"ValidationGroup="Footer"ControlToValidate="txtAccName_Footer"Display="dynamic"ErrorMessage="Enter Account Name"></asp:RequiredFieldValidator>
</td>
<td width="100px">
<asp:TextBox ID="txtPhone_Footer"CssClass="form-control"runat="server"Width="100px"/>
</td>
<td width="100px">
<asp:TextBox ID="txtFax_Footer"CssClass="form-control"runat="server"Width="100px"/>
</td>
<td width="120px">
<asp:TextBox ID="txtEmail_Footer"CssClass="form-control"runat="server"Width="120px"/>
</td>
<td width="100px">
<asp:TextBox ID="txtWebsite_Footer"CssClass="form-control"runat="server"Width="120px"/>
</td>
<td width="50px">
<asp:ImageButton ID="cmdInsert"CommandName="Add"ValidationGroup="Footer"ToolTip="Add Account" runat="server" ImageUrl="~/images/add.gif"></asp:ImageButton>
</td>
</tr>
</table>
</FooterTemplate>
</asp:DataList>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B7: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
namespace Insert_Update_DeleteRecordsInDatalist
{
public partial class _Default : System.Web.UI.Page
{
#region"Private Methods"
private voidDeleteAccount(int ItemID)
{
SqlDataProvider objSQL = newSqlDataProvider();
objSQL.RunSQL("Pro_Accounts_Delete", new ObjectPara("@ItemID", ItemID));
BindAccount();
}
private intEditAccount(int ItemID, string AccountCode, stringAccName, string AccPhone, string AccFAX, stringAccWebsite, string AccEmail, string Command)
{
SqlDataProvider objSQL = newSqlDataProvider();
int iError = -1;
if (Command == "Edit")
{
iError = Convert.ToInt32(objSQL.RunSQL("Pro_Accounts_Update", new ObjectPara("@AccountID", ItemID), new ObjectPara("@AccountCode", AccountCode), new ObjectPara("@AccName", AccName), new ObjectPara("@AccAddress", ""), new ObjectPara("@AccPhone", AccPhone), new ObjectPara("@AccFAX", AccFAX), new ObjectPara("@AccEmail", AccEmail), new ObjectPara("@AccWebsite", AccWebsite), new ObjectPara("@AccDesc", "")));
}
else
{
iError = (int)objSQL.RunSQL("Pro_Accounts_Add", new ObjectPara("@AccountCode", AccountCode), new ObjectPara("@AccName", AccName), new ObjectPara("@AccAddress", ""), new ObjectPara("@AccPhone", AccPhone), new ObjectPara("@AccFAX", AccFAX), new ObjectPara("@AccEmail", AccEmail), new ObjectPara("@AccWebsite", AccWebsite), new ObjectPara("@AccDesc", ""));
}
return iError;
}
#endregion
#region"Bind Data"
private voidBindAccount()
{
DataTable objBind = newDataTable();
objBind = BindData(txtSearch.Text);
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
dlObject.DataSource = objBind;
dlObject.DataBind();
trMessage.Visible = false;
dlObject.Visible = true;
}
else
{
trMessage.Visible = true;
dlObject.Visible = false;
lblMessage.Text = "No Data";
}
updatePanel.Update();
}
}
public static DataTable BindData(stringKeyword)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Accounts_List", new ObjectPara("@Keyword", Keyword.Trim()), new ObjectPara("@SortField", "CreatedDate"), new ObjectPara("@SortType", "DESC"));
return objBind;
}
#endregion
#region"Datalist Methods"
protected voiddlObject_EditCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgse)
{
dlObject.EditItemIndex = e.Item.ItemIndex;
BindAccount();
}
protected voiddlObject_ItemCommand(object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "Add")
{
bool IsAdded = false;
string AccountName = "";
TextBox txtAccountCode = (TextBox)e.Item.FindControl("txtAccountCode_Footer");
TextBox txtAccName = (TextBox)e.Item.FindControl("txtAccName_Footer");
TextBox txtAccPhone = (TextBox)e.Item.FindControl("txtPhone_Footer");
TextBox txtFax = (TextBox)e.Item.FindControl("txtFAX_Footer");
TextBox txtWebsite = (TextBox)e.Item.FindControl("txtWebsite_Footer");
TextBox txtEmail = (TextBox)e.Item.FindControl("txtEmail_Footer");
if (txtAccName != null & !string.IsNullOrEmpty(txtAccName.Text))
{
AccountName = txtAccName.Text;
}
if (txtAccountCode != null & txtAccName != null& txtAccPhone != null & txtFax != null & txtWebsite != null& txtEmail != null)
{
IsAdded = EditAccount(-1, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Add") > 0;
}
if (IsAdded)
{
lblMessage.Text = AccountName + " has been added successfully!";
lblMessage.ForeColor = System.Drawing.Color.Green;
BindAccount();
}
else
{
lblMessage.Text = "Error while adding: " + AccountName;
lblMessage.ForeColor = System.Drawing.Color.Red;
}
trMessage.Visible = true;
}
}
protected voiddlObject_UpdateCommand(object sender, DataListCommandEventArgs e)
{
int ItemID = -1;
Label lblAccountID = (Label)dlObject.Items[e.Item.ItemIndex].FindControl("lblAccountID_Edit");
TextBox txtAccountCode = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtAccountCode");
TextBox txtAccName = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtAccountName");
TextBox txtAccPhone = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtPhone");
TextBox txtFax = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtFAX");
TextBox txtWebsite = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtWebsite");
TextBox txtEmail = (TextBox)dlObject.Items[e.Item.ItemIndex].FindControl("txtEmail");
if (lblAccountID != null)
{
ItemID =Convert.ToInt32(lblAccountID.Text);
}
if ((txtAccountCode != null) & (txtAccName != null) & (txtAccPhone != null) & (txtFax != null) & (txtWebsite != null) & (txtEmail != null))
{
EditAccount(ItemID, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Edit");
dlObject.EditItemIndex = -1;
BindAccount();
}
}
protected voiddlObject_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
ImageButton cmdDelete = (ImageButton)e.Item.FindControl("cmdDelete");
if (cmdDelete != null)
{
cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + "Are you sure you want to delete?" + "');");
cmdDelete.ToolTip = "Delete Account";
}
}
}
protected voiddlObject_DeleteCommand(object sender, DataListCommandEventArgs e)
{
int ItemID = Convert.ToInt32(dlObject.DataKeys[e.Item.ItemIndex]);
if (ItemID != -1)
{
dlObject.EditItemIndex = -1;
DeleteAccount(ItemID);
}
}
protected voiddlObject_CancelCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgse)
{
dlObject.EditItemIndex = -1;
BindAccount();
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
Page.Form.DefaultButton = cmdQuickSearch.UniqueID;
BindAccount();
}
}
catch
{
}
}
protected voidcmdQuickSearch_Click(object sender, System.EventArgs e)
{
BindAccount();
}
#endregion
}
}VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.Data
Namespace Insert_Update_DeleteRecordsInDatalist
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private Methods"
Private SubDeleteAccount(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
objSQL.RunSQL("Pro_Accounts_Delete", New ObjectPara("@ItemID", ItemID))
BindAccount()
End Sub
Private FunctionEditAccount(ByVal ItemID As Integer, ByVal AccountCode As String, ByVal AccName As String, ByVal AccPhone As String, ByVal AccFAX As String, _
ByVal AccWebsite As String, ByValAccEmail As String, ByVal Command AsString) As Integer
Dim objSQL As New SqlDataProvider
Dim iError As Integer = -1
If Command = "Edit"Then
iError = objSQL.RunSQL("Pro_Accounts_Update", New ObjectPara("@AccountID", ItemID), _
NewObjectPara("@AccountCode", AccountCode), _
New ObjectPara("@AccName", AccName), _
New ObjectPara("@AccAddress", ""), _
New ObjectPara("@AccPhone", AccPhone), _
New ObjectPara("@AccFAX", AccFAX), _
New ObjectPara("@AccEmail", AccEmail), _
New ObjectPara("@AccWebsite", AccWebsite), _
New ObjectPara("@AccDesc", ""))
Else
iError = objSQL.RunSQL("Pro_Accounts_Add", New ObjectPara("@AccountCode", AccountCode), _
New ObjectPara("@AccName", AccName), _
New ObjectPara("@AccAddress", ""), _
New ObjectPara("@AccPhone", AccPhone), _
New ObjectPara("@AccFAX", AccFAX), _
New ObjectPara("@AccEmail", AccEmail), _
New ObjectPara("@AccWebsite", AccWebsite), _
New ObjectPara("@AccDesc", ""))
End If
Return iError
End Function
#End Region
#Region "Bind Data"
Private SubBindAccount()
Dim objBind As New DataTable
objBind = BindData(txtSearch.Text)
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
dlObject.DataSource = objBind
dlObject.DataBind()
trMessage.Visible = False
dlObject.Visible = True
Else
trMessage.Visible = True
dlObject.Visible = False
lblMessage.Text = "No Data"
End If
updatePanel.Update()
End If
End Sub
Public Shared Function BindData(ByValKeyword As String) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", Keyword.Trim), _
New ObjectPara("@SortField", "CreatedDate"), _
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "Datalist Methods"
Private SubdlObject_EditCommand(ByVal source As Object, ByVal e AsSystem.Web.UI.WebControls.DataListCommandEventArgs) Handles dlObject.EditCommand
dlObject.EditItemIndex = e.Item.ItemIndex
BindAccount()
End Sub
Private SubdlObject_ItemCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs) HandlesdlObject.ItemCommand
If e.CommandName = "Add"Then
With dlObject
Dim IsAdded AsBoolean = False
DimAccountName As String= ""
Dim txtAccountCode As TextBox = DirectCast(e.Item.FindControl("txtAccountCode_Footer"), TextBox)
Dim txtAccName AsTextBox = DirectCast(e.Item.FindControl("txtAccName_Footer"), TextBox)
Dim txtAccPhone AsTextBox = DirectCast(e.Item.FindControl("txtPhone_Footer"), TextBox)
Dim txtFax AsTextBox = DirectCast(e.Item.FindControl("txtFAX_Footer"), TextBox)
Dim txtWebsite AsTextBox = DirectCast(e.Item.FindControl("txtWebsite_Footer"), TextBox)
Dim txtEmail AsTextBox = DirectCast(e.Item.FindControl("txtEmail_Footer"), TextBox)
If NottxtAccName Is NothingAnd txtAccName.Text <> "" Then
AccountName = txtAccName.Text
End If
If NottxtAccountCode Is NothingAnd NottxtAccName Is NothingAnd NottxtAccPhone Is Nothing_
And NottxtFax Is NothingAnd NottxtWebsite Is NothingAnd NottxtEmail Is NothingThen
IsAdded = EditAccount(-1, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Add") > 0
End If
If IsAdded Then
lblMessage.Text = AccountName & " has been added successfully!"
lblMessage.ForeColor = System.Drawing.Color.Green
BindAccount()
Else
lblMessage.Text = "Error while adding: " & AccountName
lblMessage.ForeColor = System.Drawing.Color.Red
End If
trMessage.Visible = True
End With
End If
End Sub
Private SubdlObject_UpdateCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs) HandlesdlObject.UpdateCommand
With dlObject
Dim ItemID AsInteger = -1
Dim lblAccountID As Label = DirectCast(.Items(e.Item.ItemIndex).FindControl("lblAccountID_Edit"), Label)
Dim txtAccountCode As TextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtAccountCode"), TextBox)
Dim txtAccName AsTextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtAccountName"), TextBox)
Dim txtAccPhone AsTextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtPhone"), TextBox)
Dim txtFax AsTextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtFAX"), TextBox)
Dim txtWebsite AsTextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtWebsite"), TextBox)
Dim txtEmail AsTextBox = DirectCast(.Items(e.Item.ItemIndex).FindControl("txtEmail"), TextBox)
If NotlblAccountID Is NothingAnd lblAccountID.Text <> "" Then
ItemID = lblAccountID.Text
End If
If NottxtAccountCode Is NothingAnd NottxtAccName Is NothingAnd NottxtAccPhone Is Nothing_
And NottxtFax Is NothingAnd NottxtWebsite Is NothingAnd NottxtEmail Is NothingThen
EditAccount(ItemID, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text, "Edit")
dlObject.EditItemIndex = -1
BindAccount()
End If
End With
End Sub
Private SubdlObject_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs) HandlesdlObject.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim cmdDelete AsImageButton = DirectCast(e.Item.FindControl("cmdDelete"), ImageButton)
If cmdDelete IsNotNothing Then
cmdDelete.Attributes.Add("onClick", "javascript:return confirm('"& "Are you sure you want to delete?"& "');")
cmdDelete.ToolTip = "Delete Account"
End If
End If
End Sub
Private SubdlObject_DeleteCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs) HandlesdlObject.DeleteCommand
Dim ItemID As Integer = CType(dlObject.DataKeys(e.Item.ItemIndex), Integer)
If ItemID <> -1 Then
dlObject.EditItemIndex = -1
DeleteAccount(ItemID)
End If
End Sub
Private SubdlObject_CancelCommand(ByVal source As Object, ByVal e AsSystem.Web.UI.WebControls.DataListCommandEventArgs) Handles dlObject.CancelCommand
dlObject.EditItemIndex = -1
BindAccount()
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindAccount()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindAccount()
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment