Tạo cột động sử dụng Data SQL Server trong Gridview nâng cao
(Cách tạo Columns động sử dụng Data SQL Server cho Gridview) – Các bài viết trước thủ thuật tin học đã giới thiệu với các bạn cách tạo Colunms động cho Gridview. Tuy nhiên các cách xây dựng đó chỉ áp dụng đối với các BoundField, bài viết này ngoài việc tạo các cột dạng BoundField sẽ có thêm dạng TemplateField. Không những thế ví dụ này còn cho phép khai báo thêm URL cho các Control Hyperlink.
- 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 Bảng ColumnSettings có cấu trúc phía dưới trong CSDL SQL Server
STT | Tên trường | Kiểu trường | Ghi chú |
1 | FieldID | Int | Trường tự tăng |
2 | FieldName | nvarchar(100) | |
3 | FieldTitle | nvarchar(100) | |
3 | CommandArgument | nvarchar(100) | |
4 | Alignment | nvarchar(25) | |
5 | Format | nvarchar(100) | |
6 | IsControl | nvarchar(100) | |
7 | URL | nvarchar(100) | |
8 | IsVisible | Bit | |
9 | SortOrder | Int |
- B5: Nhập dữ liệu cho bảng ColumnSettings
- 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
Go
CREATE PROCEDURE [dbo].[Pro_Accounts_Get]
@AccountID int
AS
SELECT * FROM Accounts
WHERE
AccountID = @AccountID
Go
CREATE PROCEDURE [dbo].[Pro_ColumnSettings_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 ColumnSettings'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (FieldName like N''%' +@Keyword+'%''
Or FieldTitle 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='SortOrder'
Begin
set @strOrder =' Order by SortOrder'
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 DynamicallyColumnsGridView
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
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
Public Class HyperLinkColumnTemplate
Inherits System.Web.UI.Page
Implements System.Web.UI.ITemplate
Private mobjTemplateType As
System.Web.UI.WebControls.ListItemType
Private objGrid As GridView
Private sControlID As
String
Private sCaption As String
Private sColumnName As
String
Private sHyperLink As
String
Private sCommandArgument As
String
Private ItemID As Integer
Sub New(ByVal MyGrid As GridView, ByVal
ControlID As String,
ByVal Caption As
String, ByVal
ColumnName As String,
ByVal CommandArgument As
String, ByVal
HyperLink As String,
ByVal Type As
System.Web.UI.WebControls.ListItemType)
objGrid = MyGrid
mobjTemplateType = Type
sControlID = ControlID
sCaption = Caption
sColumnName = ColumnName
sCommandArgument = CommandArgument
sHyperLink = HyperLink
End Sub
Public Sub
InstantiateIn(ByVal container As System.Web.UI.Control)
Implements System.Web.UI.ITemplate.InstantiateIn
Dim objHyperLink As
System.Web.UI.WebControls.HyperLink
Select
Case mobjTemplateType
Case Web.UI.WebControls.ListItemType.Item, _
Web.UI.WebControls.ListItemType.AlternatingItem,
_
Web.UI.WebControls.ListItemType.SelectedItem
objHyperLink = New
System.Web.UI.WebControls.HyperLink
With objHyperLink
.ID = "lnk" & sControlID
.Text = sCaption
AddHandler objHyperLink.DataBinding, AddressOf
HyperLinkItem_DataBinding
End With
container.Controls.Add(objHyperLink)
End Select
End Sub
Private Sub
HyperLinkItem_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim ItemID As Integer = -1
Dim HyperLinkItem As HyperLink = DirectCast(sender,
HyperLink)
Dim CurrentRow As GridViewRow = DirectCast(HyperLinkItem.NamingContainer,
GridViewRow)
Dim CurrentDataItem As
Object = DataBinder.Eval(CurrentRow.DataItem,
sColumnName)
If sCommandArgument <> ""
Then
ItemID = DataBinder.Eval(CurrentRow.DataItem,
sCommandArgument)
End If
With HyperLinkItem
.Text = CurrentDataItem.ToString()
If sHyperLink <> "" Then
.NavigateUrl = String.Format(sHyperLink,
ItemID)
End If
End With
End Sub
End Class
Public Class GridViewColumnTemplate
Public Sub
AddColumnHyperLink(ByVal grvObject As GridView, ByVal Title As String, ByVal
ColumnName As String,
ByVal KeyName As
String, ByVal
URL As String, ByVal Align As String)
Dim objTemplateColumn As
System.Web.UI.WebControls.TemplateField
Dim strCellPrefix As String
objTemplateColumn = New
System.Web.UI.WebControls.TemplateField
objTemplateColumn.ItemTemplate = New HyperLinkColumnTemplate(grvObject, ColumnName,
ColumnName, ColumnName, KeyName, URL, ListItemType.Item)
objTemplateColumn.HeaderText = Title
strCellPrefix = Title
With objTemplateColumn
Select Case
Align.ToLower
Case "left"
.ItemStyle.HorizontalAlign = HorizontalAlign.Left
Case "right"
.ItemStyle.HorizontalAlign = HorizontalAlign.Right
Case "center"
.ItemStyle.HorizontalAlign = HorizontalAlign.Center
End Select
.HeaderStyle.CssClass = strCellPrefix.Replace("[L]",
"") & "Header"
.ItemStyle.CssClass = strCellPrefix.Replace("[L]",
"") & "Cell"
End With
grvObject.Columns.Add(objTemplateColumn)
End Sub
Public Sub
AddBoundColumn(ByVal grvObject As GridView, ByVal Title As String, ByVal
DataField As String,
ByVal Align As String, ByVal Format As String)
Dim objBoundColumn As
System.Web.UI.WebControls.BoundField
objBoundColumn = New
System.Web.UI.WebControls.BoundField
With objBoundColumn
.DataField = DataField
If Format <> "" Then
.DataFormatString = Format
End If
.HeaderText = Title
Select Case
Align.ToLower
Case "left"
.ItemStyle.HorizontalAlign = HorizontalAlign.Left
Case
"right"
.ItemStyle.HorizontalAlign = HorizontalAlign.Right
Case "center"
.ItemStyle.HorizontalAlign = HorizontalAlign.Center
End Select
End With
objBoundColumn.HeaderStyle.CssClass = Title.Replace("[L]", "")
& "Header"
objBoundColumn.ItemStyle.CssClass = Title.Replace("[L]", "")
& "Cell"
grvObject.Columns.Add(objBoundColumn)
End Sub
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B8: Mở file Default.aspxdưới dạng HTML và nhập mã HTML
<%@ Page Title="Dynamically add BoundField and TemplateField Columns to GridView in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="DynamicallyColumnsGridView._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<h3>
Dynamically add Columns to GridView in ASP.Net
</h3>
<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="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" />
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B9: Viết Code cho file Default.aspx
'Visit
http://thuthuatlaptrinh.blogspot.com for more ASP.NET Tutorials
Imports System.Data.SqlClient
Namespace DynamicallyColumnsGridView
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Members"
Private oColumnTemplate As
New GridViewColumnTemplate
#End Region
#Region "ColumnSettings"
Private Function
BindColumnSettings() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As New DataTable
'Caching
If Cache("Cache_DynamicColumns")
Is Nothing Then
objBind = objSQL.FillTable("Pro_ColumnSettings_List",
New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New
ObjectPara("@SortField",
"SortOrder"), _
New ObjectPara("@IsVisible", 1))
Cache("Cache_DynamicColumns")
= objBind
Else
objBind = CType(Cache("Cache_DynamicColumns"), DataTable)
End If
Return objBind
End Function
Private Sub
LoadColumnSettings()
Dim objSQL As New SqlDataProvider
Dim objBind As New DataTable
Dim sControl As String = ""
Dim sFieldTitle As String = ""
Dim sFieldName As String = ""
Dim sCommandArgument As
String = ""
Dim sURL As String = ""
Dim sAlignment As String = ""
Dim sFormat As String = ""
Dim b_Visible As String = ""
grvObject.Columns.Clear()
objBind = BindColumnSettings()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
For Each
row As DataRow
In objBind.Rows
sControl = "" : sCommandArgument = ""
If Not IsDBNull(row("IsVisible")) Then
b_Visible = row("IsVisible").ToString()
End If
If b_Visible Then
If Not IsDBNull(row("FieldName")) Then
sFieldName =
row("FieldName").ToString()
End If
If
Not IsDBNull(row("FieldTitle"))
Then
sFieldTitle =
row("FieldTitle").ToString()
End If
If Not IsDBNull(row("CommandArgument")) Then
sCommandArgument = row("CommandArgument").ToString()
End If
If Not IsDBNull(row("Alignment")) Then
sAlignment =
row("Alignment").ToString()
End If
If Not IsDBNull(row("Format")) Then
sFormat = row("Format").ToString()
End If
If Not IsDBNull(row("URL")) Then
sURL = row("URL").ToString()
End If
If Not IsDBNull(row("IsControl")) Then
sControl = row("IsControl").ToString()
End
If
If sControl = "Hyperlink"
Then
oColumnTemplate.AddColumnHyperLink(grvObject, sFieldTitle, sFieldName,
sCommandArgument, sURL, sAlignment)
Else
oColumnTemplate.AddBoundColumn(grvObject, sFieldTitle, sFieldName,
sAlignment, sFormat)
End If
End If
Next
End If
End If
End Sub
#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_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
LoadColumnSettings()
BindAccount()
If Page.IsPostBack = False Then
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
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
<%@ Page
Title="View"
Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="View.aspx.vb"
Inherits="DynamicallyColumnsGridView.View"
%>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"
cellspacing="5"
border="0"
width="60%">
<tr>
<td>
<div
class="panel
panel-default">
<div
class="panel-heading">
<asp:label id="lblHeader" runat="server" Text="VIEW DATA"></asp:label>
</div>
<div
class="panel-body">
<table width="100%"
cellpadding="2"
cellspacing="3">
<tr>
<td colspan="4">
<asp:Label ID="lblItemID"
Visible="false"
runat="server"/>
</td>
</tr>
<tr>
<td>
<asp:label id="plAccountCode"
runat="server"
CssClass="label"
Text="Account
Code"></asp:label>
</td>
<td colspan="3">
<asp:Label ID="lblAccCode"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccName"
runat="server"
CssClass="label"
Text="Account Name"></asp:Label>
</td>
<td colspan="3">
<asp:Label ID="lblAccName"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccAddress"
runat="server"
CssClass="label"
Text="Address"></asp:Label>
</td>
<td colspan="3">
<asp:Label ID="lblAccAddress"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td style="width:18%;">
<asp:Label ID="plPhone"
runat="server"
CssClass="label"
Text="Phone"></asp:Label>
</td>
<td style="width:40%;">
<asp:Label ID="lblAccPhone"
runat="server"></asp:Label>
</td>
<td style="width:10%;">
<asp:Label ID="plAccFax"
runat="server"
CssClass="label"
Text="Fax"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccFax"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plAccEmail"
runat="server"
CssClass="label"
Text="Email"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccEmail"
runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="plWebsite"
runat="server"
CssClass="label"
Text="Website"></asp:Label>
</td>
<td>
<asp:Label ID="lblAccWebsite"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="plDescription"
runat="server"
CssClass="label"
Text="Description"></asp:Label>
</td>
<td colspan="3">
<asp:Label id="lblDescription"
runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
<div
class="modal-footer">
<asp:LinkButton id="cmdCancel" runat="server" CssClass="btn btn-small" Causesvalidation="false">
<i class="icon-back"></i> <asp:label id="lblBack" runat="server" Text="Back"></asp:label>
</asp:LinkButton>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>
- B11: Viết Code cho file View.aspx
Namespace DynamicallyColumnsGridView
Public Class View
Inherits System.Web.UI.Page
#Region "Private
Members"
Private ItemID As Integer = -1
#End Region
#Region "Get Info"
Private Sub GetInfo(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
Dim objInfo As DataRow = objSQL.GetRow("Pro_Accounts_Get",
New ObjectPara("@AccountID", ItemID))
If Not objInfo Is Nothing Then
With objInfo
If Not
IsDBNull(objInfo("AccountCode")) Then
lblAccCode.Text =
objInfo("AccountCode")
End If
If Not
IsDBNull(objInfo("AccName")) Then
lblAccName.Text =
objInfo("AccName")
End If
If Not
IsDBNull(objInfo("AccAddress")) Then
lblAccAddress.Text =
objInfo("AccAddress")
End If
If Not
IsDBNull(objInfo("AccPhone")) Then
lblAccPhone.Text =
objInfo("AccPhone")
End If
If Not
IsDBNull(objInfo("AccFAX")) Then
lblAccFax.Text =
objInfo("AccFAX")
End If
If Not
IsDBNull(objInfo("AccEmail")) Then
lblAccEmail.Text =
objInfo("AccEmail")
End If
If Not
IsDBNull(objInfo("AccWebsite")) Then
lblAccWebsite.Text =
objInfo("AccWebsite")
End If
If Not
IsDBNull(objInfo("AccDesc")) Then
lblDescription.Text =
objInfo("AccDesc")
End If
End With
End If
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 Not
Request.QueryString("ItemID") Is Nothing Then
ItemID = Int32.Parse(Request.QueryString("ItemID"))
End If
If Page.IsPostBack = False Then
GetInfo(ItemID)
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdCancel.Click
Response.Redirect("Default.aspx")
End Sub
#End Region
End Class
End Namespace
Sau khi chạy Project, khi click vào các giá trị ở cột Code và Name chương trình sẽ chuyển đến trang View.aspx hiển thị thông tin chi tiết về khách hàng.
Chúc các bạn thành công!
Quang Bình
No Comment to " Tạo cột động sử dụng Data SQL Server trong Gridview nâng cao "