Nhúng Control AJAX HoverMenu vào GridView trong Asp.net
(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 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 sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
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 Object
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
Return cmd.ExecuteScalar
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
GetRow(ByVal ProcName As
String, ByVal ParamArray Para() As ObjectPara) As DataRow
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
For Each
p As ObjectPara
In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
adap.Fill(tb)
If tb.Rows.Count Then
Return tb.Rows(0)
End
If
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 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: 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
<%@ Page
Title="AJAX HoverMenu
Example in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"
Inherits="AJAXHoverMenu._Default"
%>
<%@ Register
Assembly="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>
<td
align="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>
<tr
id="trMessage"
runat="server"
visible="false">
<td
colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td
colspan="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%">
<AlternatingRowStyle
CssClass="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>
<td
align="left"
width="10%">
<asp:Label ID="lblAccountCode"
runat="server"
Text='<%# Eval("AccountCode") %>' />
</td>
<td
align="left"
width="20%">
<asp:Label ID="lblAccName"
runat="server"
Text='<%#Eval("AccName") %>' />
</td>
<td
align="left"
width="15%">
<asp:Label ID="lblAccPhone"
runat="server"
Text='<%# Eval("AccPhone") %>' />
</td>
<td
width="15%">
<asp:Label ID="lblAccFAX"
runat="server"
Text='<%# Eval("AccFAX") %>' />
</td>
<td
width="15%">
<asp:Label ID="lblAccWebsite"
runat="server"
Text='<%# Eval("AccWebsite") %>' />
</td>
<td
align="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>
<td
width="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:RequiredFieldValidator
ID="valAccountCode"
CssClass="NormalRed"
runat="server"
ControlToValidate="txtAccountCode"
Display="dynamic"
ErrorMessage="Enter
Code"></asp:RequiredFieldValidator>
</td>
<td
width="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>
<td
width="15%">Fax:<br />
<asp:TextBox ID="txtFax" runat="server"
Text='<%# Bind("AccFAX") %>' Width="100" />
</td>
<td
width="15%">Website:<br />
<asp:TextBox ID="txtWebsite"
runat="server"
Text='<%# Bind("AccWebsite") %>' Width="150" />
</td>
<td
width="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 Sub
DeleteAccount(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
objSQL.RunSQL("Pro_Accounts_Delete",
New ObjectPara("@ItemID", ItemID))
BindAccount()
End Sub
Private Sub
UpdateAccount(ByVal ItemID As Integer, ByVal AccountCode As String, ByVal AccName
As String, ByVal AccPhone As String, ByVal AccFAX As String, _
ByVal AccWebsite As String, ByVal
AccEmail 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 Sub
BindAccount()
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(ByVal
Keyword 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 Sub
grvObject_RowUpdating(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewUpdateEventArgs)
Handles grvObject.RowUpdating
With grvObject
Dim ItemID As
Integer = -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 As
TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccName"), TextBox)
Dim txtAccPhone As
TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtAccPhone"), TextBox)
Dim txtFax As
TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtFax"), TextBox)
Dim txtWebsite As
TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtWebsite"), TextBox)
Dim txtEmail As
TextBox = DirectCast(.Rows(e.RowIndex).FindControl("txtEmail"), TextBox)
If Not
lblAccountID Is Nothing
And lblAccountID.Text <> "" Then
ItemID = lblAccountID.Text
End If
If Not
txtAccountCode Is Nothing
And Not
txtAccName Is Nothing
And Not
txtAccPhone Is Nothing
_
And Not
txtFax Is Nothing
And Not
txtWebsite Is Nothing
And Not
txtEmail Is Nothing
Then
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 Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewRowEventArgs)
Handles grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
Dim cmdDelete As
LinkButton = CType(e.Row.FindControl("cmdDelete"), LinkButton)
If cmdDelete IsNot
Nothing 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 Sub
grvObject_RowDeleting(ByVal sender As Object, ByVal e As
System.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 Sub
grvObject_RowCancelingEdit(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewCancelEditEventArgs)
Handles grvObject.RowCancelingEdit
grvObject.EditIndex = -1
BindAccount()
End Sub
Private Sub
grvObject_RowEditing(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewEditEventArgs)
Handles grvObject.RowEditing
grvObject.EditIndex = e.NewEditIndex
BindAccount()
End Sub
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindAccount()
End Sub
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, 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 Sub
cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdQuickSearch.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
No Comment to " Nhúng Control AJAX HoverMenu vào GridView trong Asp.net "