(Sử dụng AJAX HoverMenu trong Gridview) – HoverMenu là một extender trong bộ ASP.NET AJAX có thể được gắn vào bất kỳ WebControl ASP.NET nào. Khi người dùng di chuyển con trỏ chuột qua mỗi hàng của Gridview, một Menu xuất hiện hiển thị các chức năng cần sử dụng. Và người sử dụng chỉ cần kích vào các nút lệnh cần sử dụng khi Menu xuất hiện. Bài viết dưới đây sẽ hướng dẫn các bạn cách nhúng HoverMenu vào Gridview, HoverMenu sẽ gồm các chức năng: Edit, Delete, Update, Cancel.
- 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
STT | Tên trường | Kiểu trường | Ghi chú |
1 | AccountID | Int | Trường tự tăng |
2 | AccountCode | nvarchar(25) | |
3 | AccName | nvarchar(250) | |
4 | AccAddress | nvarchar(250) | |
5 | AccPhone | nvarchar(50) | |
6 | AccFAX | nvarchar(50) | |
7 | AccEmail | nvarchar(50) | |
8 | AccWebsite | nvarchar(150) | |
9 | AccDesc | nvarchar(1500) | |
10 | CreatedDate | datetime | |
11 | ModifiedDate | datetime |
- B3: Nhập dữ liệu cho bảng Accounts
- B4: Tạo các stored procedure trong SQL Server
USE[Customers]
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
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
- 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 AJAXHoverMenu
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString AsString
#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() AsString
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public FunctionFillTable(ByVal sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(sql, _connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If NotPara Is NothingThen
For Eachp As ObjectParaIn 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 FunctionRunSQL(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As Object
Try
Dim _cnn AsNew SqlConnection(_connectionString)
_cnn.Open()
Dim cmd AsNew SqlCommand(ProcName, _cnn)
cmd.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn Para
cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
Public FunctionGetRow(ByVal ProcName AsString, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb AsNew DataTable
Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Eachp As ObjectParaIn Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
adap.Fill(tb)
If tb.Rows.Count Then
Return tb.Rows(0)
EndIf
Catch ex As Exception
Return Nothing
End Try
Return Nothing
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 PropertyName() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public PropertyValue() 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: Download thư viện AjaxControlToolkit tại địa chỉ: Download
- B7: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.
- B8: Mở file Site.css nhập thêm đoạn Code phía dưới
.NormalRed
{
font-family: Tahoma, Arial, Helvetica;
font-size: 12px;
font-weight: bold;
color: #ff0000;
}
.popupMenu
{
margin : 0px!important;
background-color : White;
color : windowtext;
border : buttonshadow;
border-width : 1px;
border-style : solid;
cursor : 'default';
overflow : auto;
font-family:Calibri;
font-size:13px;
text-align : left;
list-style-type : none;
margin-left:0px;
padding-left:5px;
max-height:150px;
width:auto;
}
- B9: Mở file Default.aspxdưới dạng HTML và bổ xung Control
<%@ PageTitle="AJAX HoverMenu Example in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"Inherits="AJAXHoverMenu._Default"%>
<%@ RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
</asp:ScriptManager>
<h1>
AJAX HoverMenu Example in ASP.Net
</h1>
<br />
<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" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<tdcolspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="AccountID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
<ItemTemplate>
<asp:Panel CssClass="popupMenu"ID="PopupMenu"runat="server">
<div style="border:1px outset white;padding:2px;">
<div><asp:LinkButton ID="cmdEdit"runat="server"CommandName="Edit"CommandArgument='<%# Eval("AccountID")%>' Text="Edit" /></div>
<div><asp:LinkButton ID="cmdDelete"runat="server"CommandName="Delete"CommandArgument='<%# Eval("AccountID")%>' Text="Delete"/></div>
</div>
</asp:Panel>
<asp:Panel ID="Panel9" runat="server">
<table width="100%">
<tr>
<tdalign="left"width="10%">
<asp:Label ID="lblAccountCode"runat="server"Text='<%# Eval("AccountCode") %>' />
</td>
<tdalign="left"width="20%">
<asp:Label ID="lblAccName"runat="server"Text='<%#Eval("AccName") %>' />
</td>
<tdalign="left"width="15%">
<asp:Label ID="lblAccPhone"runat="server"Text='<%# Eval("AccPhone") %>' />
</td>
<tdwidth="15%">
<asp:Label ID="lblAccFAX"runat="server"Text='<%# Eval("AccFAX") %>' />
</td>
<tdwidth="15%">
<asp:Label ID="lblAccWebsite"runat="server"Text='<%# Eval("AccWebsite") %>' />
</td>
<tdalign="left"width="15%">
<asp:Label ID="lblAccEmail"runat="server"Text='<%# Eval("AccEmail") %>' />
</td>
</tr>
</table>
</asp:Panel>
<cc1:HoverMenuExtender ID="hme2" runat="Server"
HoverCssClass="popupHover"
PopupControlID="PopupMenu"
PopupPosition="Left"
TargetControlID="Panel9"
PopDelay="25"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Panel ID="Panel9" runat="server"Width="96%">
<table width="100%">
<tr>
<tdwidth="15%">Code:<br />
<asp:Label ID="lblAccountID"Visible="false"runat="server"Text='<%# Eval("AccountID") %>' />
<asp:TextBox ID="txtAccountCode"runat="server"Text='<%# Bind("AccountCode") %>' Width="100" />
<asp:RequiredFieldValidatorID="valAccountCode"CssClass="NormalRed"runat="server"ControlToValidate="txtAccountCode"Display="dynamic"ErrorMessage="Enter Code"></asp:RequiredFieldValidator>
</td>
<tdwidth="25%">Name:<br />
<asp:TextBox ID="txtAccName"runat="server"Text='<%# Bind("AccName") %>' Width="180" />
</td>
<td width="15%">Phone:<br />
<asp:TextBox ID="txtAccPhone"runat="server"Text='<%# Bind("AccPhone") %>' Width="80" />
</td>
<tdwidth="15%">Fax:<br />
<asp:TextBox ID="txtFax" runat="server"Text='<%# Bind("AccFAX") %>' Width="100" />
</td>
<tdwidth="15%">Website:<br />
<asp:TextBox ID="txtWebsite"runat="server"Text='<%# Bind("AccWebsite") %>' Width="150" />
</td>
<tdwidth="12%">Email:<br />
<asp:TextBox ID="txtEmail"runat="server"Text='<%# Bind("AccEmail") %>' Width="150" />
</td>
</tr>
</table>
</asp:Panel>
<cc1:HoverMenuExtender ID="hme1" runat="Server"
TargetControlID="Panel9"
PopupControlID="PopupMenu"
HoverCssClass="popupHover"
PopupPosition="Right"/>
<asp:Panel ID="PopupMenu"runat="server"CssClass="popupMenu"Width="80">
<div style="border:1px outset white">
<asp:LinkButton ID="cmdUpdate"runat="server"CausesValidation="True"CommandName="Update"Text="Update"/>
<br/>
<asp:LinkButton ID="cmdCancel"runat="server"CausesValidation="False"CommandName="Cancel"Text="Cancel"/>
</div>
</asp:Panel>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B10: Viết Code cho file Default.aspx
Imports AjaxControlToolkit
Namespace AJAXHoverMenu
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 SubUpdateAccount(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)
Dim objSQL As New SqlDataProvider
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", ""))
BindAccount()
End Sub
#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
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
Else
trMessage.Visible = True
grvObject.Visible = False
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 "GridView Methods"
Private SubgrvObject_RowUpdating(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewUpdateEventArgs) Handles grvObject.RowUpdating
With grvObject
Dim ItemID AsInteger = -1
Dim lblAccountID As Label = DirectCast(.Rows(e.RowIndex).FindControl("lblAccountID"), Label)
Dim txtAccountCode As TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccountCode"), TextBox)
Dim txtAccName AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccName"), TextBox)
Dim txtAccPhone AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccPhone"), TextBox)
Dim txtFax AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtFax"), TextBox)
Dim txtWebsite AsTextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtWebsite"), TextBox)
Dim txtEmail AsTextBox = DirectCast(.Rows(e.RowIndex).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
UpdateAccount(ItemID, txtAccountCode.Text, txtAccName.Text, txtAccPhone.Text, txtFax.Text, txtWebsite.Text, txtEmail.Text)
grvObject.EditIndex = -1
BindAccount()
End If
End With
End Sub
Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewRowEventArgs) Handles grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim cmdDelete AsLinkButton = CType(e.Row.FindControl("cmdDelete"), LinkButton)
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 SubgrvObject_RowDeleting(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvObject.RowDeleting
Dim ItemID As Integer = CType(grvObject.DataKeys(e.RowIndex).Value, Integer)
If ItemID <> -1 Then
DeleteAccount(ItemID)
End If
End Sub
Private SubgrvObject_RowCancelingEdit(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles grvObject.RowCancelingEdit
grvObject.EditIndex = -1
BindAccount()
End Sub
Private SubgrvObject_RowEditing(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewEditEventArgs) Handles grvObject.RowEditing
grvObject.EditIndex = e.NewEditIndex
BindAccount()
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
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
Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment