Tạo Dropdown Menu nâng cao trong Asp.Net Gridview
(Cách tạo Action Menu nâng cao trong Gridview) – Trong bài viết "Tạo Dropdown Menu trong Asp.Net Gridview", thủ thuật tin học đã giới thiệu với các bạn cách tạo Menu trong Gridview. Với bài viết trước danh sách Menu được tạo cố định, nhưng bài viết này thông tin Menu sẽ được lấy từ trong Database SQL Server như: tên Menu, đường dẫn, đối số….
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Accounts có cấu trúc phía dưới
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 Bảng ActionMenu có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | MenuID | Int | Trường tự tăng |
2 | MenuOrder | Int | |
3 | MenuName | nvarchar(250) | |
4 | CommandArgument | nvarchar(250) | |
5 | URL | nvarchar(250) | |
6 | IsVisible | bit |
- B6: Tạo 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
CREATE PROCEDURE [dbo].[Pro_Menu_List]
@Keyword nvarchar(250),
@SortField nvarchar(50),
@IsVisible bit
AS
declare
@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from ActionMenu'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (MenuName like N''%'+@Keyword+'%'')'
if @IsVisible=0
set @strWhere= @strWhere +' and (IsVisible=0 Or
IsVisible Is Null)'
if @IsVisible=1
set @strWhere= @strWhere +' and (IsVisible=1)'
if @SortField=''
Begin
set @strOrder =' Order by MenuOrder'
End
Else
Begin
set @strOrder =' Order by ' + @SortField
End
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go
- B7: 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 DropdownMenuGridView
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
#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
- B8: Tạo thư mục Js trong Project
- B9: Download các file css và js tại đây, copy file jquery.dropdown.css vào thư mục Styles
- B10: Copy file js jquery.dropdown.js vào thư mục js
- B11: Copy file action.gif vào thư mục Images Project
- B12: Tạo các file Edit.aspx, View.aspx trong Project
- B13: Tạo thư mục UserControls, tạo file ActionMenu.ascx trong thư mục vừa tạo
- B14: Mở file ActionMenu. ascx dạng HTML và nhập mã HTML
<%@ Control
Language="vb"
AutoEventWireup="false"
CodeBehind="ActionMenu.ascx.vb"
Inherits="DropdownMenuGridView.UserControls.ActionMenu"
%>
<asp:Label ID="lblItemID" Visible="false" runat="server"/>
<div class="dropdownmenu-menu">
<asp:DataList id="lstMenu"
cellspacing="0"
cellpadding="0"
RepeatDirection="vertical"
Runat="Server"
Width="100%"
EnableViewState="false">
<ItemTemplate>
<table cellpadding="0"
cellspacing="0"
width="100%">
<tr>
<td>
<asp:HyperLink id="lnkMenu" Text='<%# Eval("MenuName") %>' runat="server"
/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
- B15: Viết Code cho file ActionMenu.ascx
Namespace DropdownMenuGridView.UserControls
Partial Class ActionMenu
Inherits System.Web.UI.UserControl
#Region "Private
Members"
Private ItemID As Integer
#End Region
#Region "Event
Click"
Public Event
ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataListCommandEventArgs)
#End Region
#Region "Datalist
Methods"
Private Sub
lstMenu_ItemCommand(ByVal source As Object, ByVal e As
System.Web.UI.WebControls.DataListCommandEventArgs)
Handles lstMenu.ItemCommand
RaiseEvent
ItemCommand(source, e)
End Sub
Private Sub
lstMenu_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs)
Handles lstMenu.ItemDataBound
If (e.Item.ItemType = ListItemType.Item
Or e.Item.ItemType = ListItemType.AlternatingItem)
Then
Dim MenuID As
Integer = DataBinder.Eval(e.Item.DataItem,
"MenuID")
Dim MenuName As
String = DataBinder.Eval(e.Item.DataItem,
"MenuName")
Dim URL As String = DataBinder.Eval(e.Item.DataItem, "URL")
Dim lnkMenu As
HyperLink = DirectCast(e.Item.FindControl("lnkMenu"), HyperLink)
Dim CommandArgument As String = ""
If lblItemID.Text <> "" Then
CommandArgument = lblItemID.Text
End If
If lblItemID.Text <> "" Then
ItemID = lblItemID.Text
End If
If Not
lnkMenu Is Nothing
Then
lnkMenu.NavigateUrl = String.Format(URL,
ItemID)
End If
End If
End Sub
#End Region
#Region "Pulbic
Methods"
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Menu_List", New ObjectPara("@Keyword", ""),
_
New ObjectPara("@SortField", "MenuOrder"),
_
New ObjectPara("@IsVisible", 1))
Return objBind
End Function
Public Sub BindMenu(ByVal ItemID As Integer)
Dim objBind As New DataTable
objBind = BindData()
If ItemID <> -1 And
ItemID <> 0 Then
lblItemID.Text = ItemID
End If
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
lstMenu.DataSource = objBind
lstMenu.DataBind()
End If
End If
End Sub
#End Region
End Class
End Namespace
- B16: Mở file Default.aspxdưới dạng HTML và nhập mã HTML
<%@ Page
Title="Dropdown
Menu in Asp.Net GridView" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"
Inherits="DropdownMenuGridView._Default"
%>
<%@ Register
TagPrefix="ActionMenu"
TagName="Menu"
Src="~/UserControls/ActionMenu.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<h3>
Dropdown Menu in Asp.Net GridView
</h3>
<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="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle" />
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText = "Number">
<ItemStyle HorizontalAlign="Center"
Width="2%"></ItemStyle>
<ItemTemplate>
<asp:Label ID="lblRowNumber"
Text='<%# Container.DataItemIndex + 1 %>' runat="server"
/>
<asp:Label ID="lblItemID"
Text='<%# Eval("AccountID") %>' Visible="false"
runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AccountCode">
<ItemStyle Width="10%"></ItemStyle>
<ItemTemplate>
<span id="spActionMenu"
runat="server"
class="actionmenu">
<asp:Label ID="lblAccountCode"
Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
<asp:Image ID="imgActionMenu"
runat="server"></asp:Image>
</span>
<div id="ucdropdownmenu"
runat="server"
class="dropdownmenu
dropdownmenu-tip">
<ActionMenu:Menu ID="ucActionMenu"
runat="server"
/>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="15%"
DataField="AccName"
HeaderText="AccountName"
/>
<asp:BoundField ItemStyle-Width="10%"
DataField="AccPhone"
HeaderText="Phone"
/>
<asp:BoundField ItemStyle-Width="10%"
DataField="AccFAX"
HeaderText="FAX"
/>
<asp:BoundField ItemStyle-Width="15%"
DataField="AccEmail"
HeaderText="Email"
/>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B17: Viết Code cho file Default.aspx
'Visit
http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.Data.SqlClient
Namespace DropdownMenuGridView
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
#End Region
#Region "Bind Data"
Private Sub
BindAccount()
Dim objBind As New DataTable
objBind = BindData()
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
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@SortField", "CreatedDate"),
_
New ObjectPara("@SortType", "DESC"))
Return objBind
End Function
#End Region
#Region "GridView Methods"
Private Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles
grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
Dim ItemID As
Integer = DataBinder.Eval(e.Row.DataItem,
"AccountID")
Dim ctlActionMenu As DropdownMenuGridView.UserControls.ActionMenu = CType(e.Row.FindControl("ucActionMenu"),
DropdownMenuGridView.UserControls.ActionMenu)
If Not
ctlActionMenu Is Nothing
Then
With ctlActionMenu
.BindMenu(ItemID)
End With
End If
Dim imgActionMenu As Image = CType(e.Row.FindControl("imgActionMenu"),
Image)
If Not
imgActionMenu Is Nothing
Then
imgActionMenu.ImageUrl = Page.ResolveUrl("Images\action.gif")
End If
Dim ucdropdownmenu As HtmlGenericControl
= DirectCast(e.Row.FindControl("ucdropdownmenu"), HtmlGenericControl)
If Not
ucdropdownmenu Is Nothing
Then
ucdropdownmenu.ID &= "_"
& ItemID
End If
Dim spActionMenu As HtmlGenericControl = DirectCast(e.Row.FindControl("spActionMenu"),
HtmlGenericControl)
If Not
spActionMenu Is Nothing
Then
spActionMenu.Attributes.Add("data-dropdown",
"#" & ucdropdownmenu.ClientID)
End If
End If
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
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
Sau khi chạy Project, khi click vào các giá trị ở cột AccountCode Menu chức năng xuất hiện và người dùng có thể lựa chọn chức năng để sử dụng.
Chúc các bạn thành công!
Quang Bình
No Comment to " Tạo Dropdown Menu nâng cao trong Asp.Net Gridview "