(Cách tạo Columns động sử dụng Data SQL Server cho Gridview) – Với việc cho phép cấu hình danh sách các cột được hiển thị trên Gridview khi có yêu cầu sẽ giúp yêu cầu được thực hiện thuận lợi và nhanh chóng hơn. Do không phải phụ thuộc vào người lập trình thêm hoặc bớt cột bằng Code mà hoàn toàn có thể thay đổi trên giao diện Web. Bài viết trước chúng tôi đã giới thiệu bài tạo Columns động bằng file XML, hôm nay chúng tôi sẽ hướng dẫn một cách khách để làm việc này. Đó là sử dụng Data SQL Server, thông tin các cột được lưu trữ trong bảng và chỉ cần thay đổi thông tin dữ liệu trong bảng là cột trên Gridview cũng thay đổi theo.
- 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) | |
4 | Alignment | nvarchar(25) | |
5 | Format | nvarchar(100) | |
6 | Width | Int | |
7 | IsVisible | Bit | |
8 | 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_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
#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 GridViewColumnTemplate
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
<%@ PageTitle="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>
<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="12"
CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"width="100%">
<AlternatingRowStyleCssClass="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 AsNew GridViewColumnTemplate
#End Region
#Region "ColumnSettings"
Private FunctionBindColumnSettings() 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 SubLoadColumnSettings()
Dim objSQL As New SqlDataProvider
Dim objBind As New DataTable
Dim sFieldTitle As String = ""
Dim sFieldName 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 Eachrow As DataRowIn objBind.Rows
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("Alignment")) Then
sAlignment = row("Alignment").ToString()
End If
If Not IsDBNull(row("Format")) Then
sFormat = row("Format").ToString()
End If
oColumnTemplate.AddBoundColumn(grvObject, sFieldTitle, sFieldName, sAlignment, sFormat)
End If
Next
End If
End If
End Sub
#End Region
#Region "Bind Data"
Private SubBindAccount()
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 FunctionBindData() 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 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
LoadColumnSettings()
BindAccount()
If Page.IsPostBack = False Then
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
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ạy Project, chương trình sẽ lấy các thông tin cột được lưu trữ tại bảng ColumnSettings để hiển thị trên Gridview.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment