(Moving GridView Rows Up & Down in a GridView) – Khi những giá trị thường xuyên được chọn trong danh sách được sắp xếp lên đầu sẽ giúp người dùng lựa chọn dễ dàng hơn khi sử dụng. Bài viết dưới đây sẽ hướng dẫn các bạn làm 1 phần quản trị để có thể dễ dàng thay đổi thứ tự ưu tiên của các bản ghi. Và chỉ cần kích các nút Up hoặc Down là thứ tự sẽ tự động được thay đổi.
- B2: Tạo Bảng Categories có cấu trúc phía dưới trong CSDL SQL Server.
- B3: Nhập dữ liệu cho bảng Categories
- B4: Tạo các stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Categories_Delete]
@ItemID int
AS
DELETE FROM Categories
WHERE
CategoryID = @ItemID
GO
create PROCEDURE [dbo].[Pro_Categories_GetByOrder]
@SortOrder int
AS
SELECT *
FROM Categories
WHERE SortOrder = @SortOrder
GO
CREATE PROCEDURE [dbo].[Pro_Categories_List]
@Keyword nvarchar(250)
AS
declare@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Categories'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (CategoryCode like N''%' +@Keyword+'%''
Or CategoryName like N''%' +@Keyword+'%''
Or Description like N''%' +@Keyword+'%'')'
set @strOrder =' Order by SortOrder'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
GO
create procedure[dbo].[Pro_Categories_UpdateOrder]
@ItemID int,
@SortOrder int
as
update Categories
set
SortOrder = @SortOrder
where CategoryID = @ItemID
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.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace MoveRowsInGridViewUpandDown
{
public class SqlDataProvider
{
#region"Membres Prives"
private string_connectionString;
#endregion
#region"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region"Proprietes"
public stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
if ((Para != null))
{
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
}
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
public object RunSQL(string ProcName, paramsObjectPara[] Para)
{
try
{
SqlConnection _cnn = new SqlConnection(_connectionString);
_cnn.Open();
SqlCommand cmd = new SqlCommand(ProcName, _cnn);
cmd.CommandType = CommandType.StoredProcedure;
foreach (ObjectParap in Para)
{
cmd.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
int result = (Int32)cmd.ExecuteScalar();
return result;
}
catch
{
return null;
}
}
public DataRowGetRow(string ProcName, params ObjectPara[] Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
foreach (ObjectParap in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
adap.Fill(tb);
if (tb.Rows != null)
{
return tb.Rows[0];
}
}
catch
{
return null;
}
return null;
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(stringPname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public object Value
{
get { return _Value; }
set { _Value = value; }
}
}
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace MoveRowsInGridViewUpDown
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 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)
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 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
End Namespace
- B6: Download các file ảnh tại đây, Copy ảnh vào thư mục Images của Project
- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="How to move the rows in the GridView Up and Down in Asp.net" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="MoveRowsInGridViewUpandDown._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<h3>
How to move the rows in the GridView Up and Down 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" OnClick="cmdQuickSearch_Click" 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" DataKeyNames="CategoryID" width="100%"
OnRowCommand="grvObject_RowCommand"
OnRowDataBound="grvObject_RowDataBound">
<AlternatingRowStyleCssClass="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"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="8%"DataField="CategoryCode"HeaderText="CategoryCode"/>
<asp:BoundField ItemStyle-Width="10%"DataField="CategoryName"HeaderText="CategoryName"/>
<asp:BoundField ItemStyle-Width="25%"DataField="Description"HeaderText="Description"/>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center"width="6%"/>
<ItemTemplate>
<asp:ImageButton ID="cmdDelete"CommandName="Delete"CommandArgument='<%# Eval("CategoryID")%>' runat="server"ImageUrl="~/images/delete.gif"CausesValidation="False"></asp:ImageButton>
<asp:ImageButton id="cmdMoveDown"runat="server"ImageUrl="~/images/dn.gif"ToolTip="Down"CausesValidation="false"CommandName="MoveDown"CommandArgument ='<%# Eval("SortOrder")%>'></asp:ImageButton>
<asp:ImageButton id="cmdMoveUp"runat="server"ImageUrl="~/images/up.gif"ToolTip="Up"CausesValidation="false"CommandName="MoveUp"CommandArgument ='<%# Eval("SortOrder")%>'></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B8: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
namespace MoveRowsInGridViewUpandDown
{
public partial class _Default : System.Web.UI.Page
{
#region"Private Methods"
private int iLastRow = 0;
#endregion
#region"Private Methods"
private void Delete(int ItemID)
{
SqlDataProvider objSQL = newSqlDataProvider();
objSQL.RunSQL("Pro_Categories_Delete", new ObjectPara("@ItemID", ItemID));
BindData();
}
#endregion
#region"Bind Data"
private voidBindData()
{
DataTable objBind = newDataTable();
objBind = GetData(txtSearch.Text);
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
iLastRow = objBind.Rows.Count - 1;
grvObject.DataSource = objBind;
grvObject.DataBind();
trMessage.Visible = false;
grvObject.Visible = true;
}
else
{
trMessage.Visible = true;
grvObject.Visible = false;
}
updatePanel.Update();
}
}
private DataTableGetData(string Keyword)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Categories_List", new ObjectPara("@Keyword", Keyword.Trim()));
return objBind;
}
#endregion
#region"Order"
private void MoveProperty(int Index, intDestIndex)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataRow objInfo = objSQL.GetRow("Pro_Categories_GetByOrder", new ObjectPara("@SortOrder", Index));
DataRow objDestInfo = objSQL.GetRow("Pro_Categories_GetByOrder", new ObjectPara("@SortOrder", DestIndex));
int ItemID = 0;
int Item_Dest = 0;
int OrderBy = 0;
int OrderBy_Dest = 0;
if (objInfo != null)
{
if (objInfo["CategoryID"] != null)
{
ItemID =Convert.ToInt32(objInfo["CategoryID"]);
}
if (objInfo["SortOrder"] != null)
{
OrderBy = Convert.ToInt32(objInfo["SortOrder"]);
}
}
if (objDestInfo != null)
{
if (objDestInfo["CategoryID"] != null)
{
Item_Dest = Convert.ToInt32(objDestInfo["CategoryID"]);
}
if (objDestInfo["SortOrder"] != null)
{
OrderBy_Dest = Convert.ToInt32(objDestInfo["SortOrder"]);
}
}
if (OrderBy != 0 & OrderBy_Dest != 0)
{
objSQL.RunSQL("Pro_Categories_UpdateOrder", new ObjectPara("@ItemID", Item_Dest), new ObjectPara("@SortOrder", OrderBy));
objSQL.RunSQL("Pro_Categories_UpdateOrder", new ObjectPara("@ItemID", ItemID), new ObjectPara("@SortOrder", OrderBy_Dest));
BindData();
}
}
private voidMovePropertyDown(int index)
{
MoveProperty(index, (index + 1));
}
private voidMovePropertyUp(int index)
{
MoveProperty(index, (index - 1));
}
#endregion
#region"GridView Methods"
protected voidgrvObject_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgse)
{
if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
{
int ItemID = -1;
ItemID =Convert.ToInt32(e.CommandArgument);
switch (e.CommandName.ToLower())
{
case"moveup":
MovePropertyUp(ItemID);
break;
case "movedown":
MovePropertyDown(ItemID);
break;
}
}
}
protected voidgrvObject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int ItemID =Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "CategoryID"));
HyperLink cmdEdit = (HyperLink)e.Row.FindControl("cmdEdit");
if (cmdEdit != null)
{
cmdEdit.ToolTip = "Edit";
}
ImageButton cmdMoveDown = (ImageButton)e.Row.FindControl("cmdMoveDown");
if (cmdMoveDown != null)
{
cmdMoveDown.ToolTip = "Move Down";
if (e.Row.RowIndex == iLastRow)
{
cmdMoveDown.Visible = false;
}
}
ImageButton cmdMoveUp = (ImageButton)e.Row.FindControl("cmdMoveUp");
if (cmdMoveUp != null)
{
cmdMoveUp.ToolTip = "Move Up";
if (e.Row.RowIndex == 0)
{
cmdMoveUp.Visible = false;
}
}
ImageButton cmdDelete = (ImageButton)e.Row.FindControl("cmdDelete");
if (cmdDelete != null)
{
string sDeleteItem = "Do you want to delete this record?";
cmdDelete.Attributes.Add("onclick", ("javascript:return confirm('" + sDeleteItem + "');"));
cmdDelete.ToolTip = "Delete";
}
}
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindData();
}
}
catch
{
}
}
protected voidcmdQuickSearch_Click(object sender, System.EventArgs e)
{
BindData();
}
#endregion
}
}
VB.Net Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO
Namespace MoveRowsInGridViewUpDown
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private Methods"
Private iLastRow As Integer = 0
#End Region
#Region "Private Methods"
Private Sub Delete(ByVal ItemID As Integer)
Dim objSQL As New SqlDataProvider
objSQL.RunSQL("Pro_Categories_Delete", New ObjectPara("@ItemID", ItemID))
BindData()
End Sub
#End Region
#Region "Bind Data"
Private SubBindData()
Dim objBind As New DataTable
objBind = GetData(txtSearch.Text.Trim)
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
iLastRow = objBind.Rows.Count - 1
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 FunctionGetData(ByVal Keyword AsString) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Categories_List", New ObjectPara("@Keyword", Keyword.Trim))
Return objBind
End Function
#End Region
#Region "Order"
Private SubMoveProperty(ByVal Index As Integer, ByVal DestIndex As Integer)
Dim objSQL As New SqlDataProvider
Dim objInfo As DataRow = objSQL.GetRow("Pro_Categories_GetByOrder", New ObjectPara("@SortOrder", Index))
Dim objDestInfo As DataRow = objSQL.GetRow("Pro_Categories_GetByOrder", New ObjectPara("@SortOrder", DestIndex))
Dim ItemID As Integer = 0
Dim Item_Dest As Integer = 0
Dim OrderBy As Integer = 0
Dim OrderBy_Dest As Integer = 0
If Not objInfo Is Nothing Then
If NotIsDBNull(objInfo("CategoryID")) Then
ItemID = objInfo("CategoryID")
End If
If NotIsDBNull(objInfo("SortOrder")) Then
OrderBy = objInfo("SortOrder")
End If
End If
If Not objDestInfo Is Nothing Then
If NotIsDBNull(objDestInfo("CategoryID")) Then
Item_Dest = objDestInfo("CategoryID")
End If
If NotIsDBNull(objDestInfo("SortOrder")) Then
OrderBy_Dest = objDestInfo("SortOrder")
End If
End If
If OrderBy <> 0 AndOrderBy_Dest <> 0 Then
objSQL.RunSQL("Pro_Categories_UpdateOrder", New ObjectPara("@ItemID", Item_Dest), New ObjectPara("@SortOrder", OrderBy))
objSQL.RunSQL("Pro_Categories_UpdateOrder", New ObjectPara("@ItemID", ItemID), New ObjectPara("@SortOrder", OrderBy_Dest))
BindData()
End If
End Sub
Private SubMovePropertyDown(ByVal index As Integer)
MoveProperty(index, (index + 1))
End Sub
Private SubMovePropertyUp(ByVal index As Integer)
MoveProperty(index, (index - 1))
End Sub
#End Region
#Region "GridView Methods"
Private SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
If e.CommandArgument.ToString <> "" Then
Dim ItemID AsInteger = -1
ItemID = e.CommandArgument
Select Casee.CommandName.ToLower
Case "moveup"
MovePropertyUp(ItemID)
Case "movedown"
MovePropertyDown(ItemID)
End Select
End If
End Sub
Private SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) HandlesgrvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim ItemID AsInteger = DataBinder.Eval(e.Row.DataItem, "CategoryID")
Dim cmdEdit AsHyperLink = CType(e.Row.FindControl("cmdEdit"), HyperLink)
If NotcmdEdit Is NothingThen
cmdEdit.ToolTip = "Edit"
End If
Dim cmdMoveDown AsImageButton = CType(e.Row.FindControl("cmdMoveDown"), ImageButton)
If NotcmdMoveDown Is NothingThen
cmdMoveDown.ToolTip = "Move Down"
If e.Row.RowIndex = iLastRow Then
cmdMoveDown.Visible = False
End If
End If
Dim cmdMoveUp AsImageButton = CType(e.Row.FindControl("cmdMoveUp"), ImageButton)
If NotcmdMoveUp Is NothingThen
cmdMoveUp.ToolTip = "Move Up"
If e.Row.RowIndex = 0 Then
cmdMoveUp.Visible = False
EndIf
End If
Dim cmdDelete AsImageButton = DirectCast(e.Row.FindControl("cmdDelete"), ImageButton)
If NotcmdDelete Is NothingThen
Dim sDeleteItem AsString = "Do you want to delete this record?"
cmdDelete.Attributes.Add("onclick", ("javascript:return confirm('"& sDeleteItem & "');"))
cmdDelete.ToolTip = "Delete"
End If
End If
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
BindData()
End If
Catch ex As Exception
End Try
End Sub
Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
BindData()
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project khi cần thay đổi thứ tự loại chỉ cần kích vào các nút Down hoặc Up thì ngoài việc thay đổi vị trí hiển thị trên Gridview chương trình sẽ tự động cập nhật thứ tự trong CSDL SQL.
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment