Sử dụng nhiều đối số trong CommandArgument trong Datalist
(How to use multiple arguments in CommandArgument in Datalist) – Nếu như trong Gridview người lập trình có thể sử dụng nhiều giá trị trong Datakes và CommandArgument. Tuy nhiên trong Datalist Datakeys không có mà chỉ có DataKeyField và nó không cho phép sử dụng nhiều giá trị trong đó. Vậy còn CommandArgument thì sao? Datalist vẫn hỗ trợ CommandArgument và cho phép sử dụng nhiều đối số trong đó. Bài viết dưới đây sẽ hướng dẫn cách bạn cách sử dụng nhiều đối số và lấy ra giá trị của từng đối số trong CommandArgument Datalist.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- B2: 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.
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 MultipleArgumentsinCommandArgument
{
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 string
ConnectionString
{
get { return
_connectionString; }
}
#endregion
#region
"Functions"
public DataTable
FillTable(string sql)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(sql,
_connectionString);
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(string
Pname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value;
}
}
public object Value
{
get { return _Value;
}
set { _Value = value;
}
}
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace MultipleArgumentsinCommandArgument
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
#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
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B3: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page
Title="How to use
multiple arguments in CommandArgument in Datalist" Language="C#"
MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="MultipleArgumentsinCommandArgument._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
How
to use multiple arguments in CommandArgument in Datalist
</h3>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<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:Datalist ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="ProductID"
width="100%"
OnRowCommand="grvObject_RowCommand"
OnRowDataBound="grvObject_RowDataBound"
OnPageIndexChanging="grvObject_PageIndexChanging">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemStyle width="25%" />
<ItemTemplate>
<asp:Label ID="lblProductName"
Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QuantityPerUnit">
<ItemStyle width="12%" />
<ItemTemplate>
<asp:Label ID="lblQuantityPerUnit"
Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitPrice">
<ItemStyle HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblUnitPrice"
Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitsInStock">
<ItemStyle HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblUnitsInStock"
Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitsOnOrder">
<ItemStyle HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblUnitsOnOrder"
Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center"
width="4%"
/>
<ItemTemplate>
<asp:ImageButton ID="cmdDetail"
CommandName="View"
CommandArgument='<%# Eval("ProductID") + "," +
Eval("SupplierID") + "," + Eval("CategoryID") %>' runat="server" ImageUrl="~/Images/icon_detail.png" CausesValidation="False"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:Datalist>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>VB.Net Code
<%@ Page
Title="How to use
multiple arguments in CommandArgument in Datalist" Language="vb"
MasterPageFile="~/Site.Master"
AutoEventWireup="false"
CodeBehind="Default.aspx.vb"
Inherits="MultipleArgumentsinCommandArgument._Default"
%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
</asp:ScriptManager>
<h3>
How
to use multiple arguments in CommandArgument in Datalist
</h3>
<asp:UpdatePanel ID="updatePanel"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2"
cellspacing="3"
width="100%">
<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:Datalist ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"
BorderColor="#cbcbcb"
BorderStyle="solid"
BorderWidth="1"
AutoGenerateColumns="false"
DataKeyNames="ProductID"
width="100%">
<AlternatingRowStyle
CssClass="GridStyle_AltRowStyle"
/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"
/>
<RowStyle CssClass="GridStyle_RowStyle"
/>
<pagerstyle cssclass="GridStyle_pagination"
/>
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemStyle width="25%" />
<ItemTemplate>
<asp:Label ID="lblProductName" Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QuantityPerUnit">
<ItemStyle HorizontalAlign="Right"
width="12%"
/>
<ItemTemplate>
<asp:Label ID="lblQuantityPerUnit" Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitPrice">
<ItemStyle width="10%" />
<ItemTemplate>
<asp:Label ID="lblUnitPrice"
Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitsInStock">
<ItemStyle HorizontalAlign="Right"
width="10%"
/>
<ItemTemplate>
<asp:Label ID="lblUnitsInStock"
Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UnitsOnOrder">
<ItemStyle HorizontalAlign="Right" width="10%" />
<ItemTemplate>
<asp:Label ID="lblUnitsOnOrder"
Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center"
width="4%"
/>
<ItemTemplate>
<asp:ImageButton ID="cmdDetail"
CommandName="View"
CommandArgument='<%# Eval("ProductID") & ","
& Eval("SupplierID") & "," &
Eval("CategoryID") %>' runat="server" ImageUrl="~/Images/icon_detail.png" CausesValidation="False"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:Datalist>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>- B4: Viết Code cho file Default.aspx
C#
//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.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MultipleArgumentsinCommandArgument
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Private Methods"
private void
ShowMessage(int ProductID, int SupplierID, int
CategoryID)
{
string sMessage = "ProductID:
" + ProductID + " - SupplierID:
" + SupplierID + " - CategoryID:
" + CategoryID;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(),
"alert", "alert('"
+ sMessage + "');", true);
}
#endregion
#region
"Bind Data"
private void
BindProduct()
{
DataTable objBind = new
DataTable();
objBind = BindData();
if (objBind != null)
{
if
(objBind.Rows.Count > 0)
{
grvObject.DataSource = objBind;
grvObject.DataBind();
trMessage.Visible = false;
grvObject.Visible = true;
updatePanel.Update();
}
else
{
trMessage.Visible = true;
grvObject.Visible = false;
}
}
}
private DataTable
BindData()
{
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Products.* From Products");
return objBind;
}
#endregion
#region "Datalist
Methods"
protected void
grvObject_RowCommand(object sender,
System.Web.UI.WebControls.DatalistCommandEventArgs
e)
{
if (e.CommandName.ToLower() != "sort" & e.CommandName.ToLower() != "page" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
{
string[] CommandArgument =
e.CommandArgument.ToString().Split(',');
int ProductID = -1;
int SupplierID = -1;
int CategoryID = -1;
if (CommandArgument.Length > 0)
{
ProductID = Convert.ToInt32(CommandArgument[0]);
SupplierID = Convert.ToInt32(CommandArgument[1]);
CategoryID = Convert.ToInt32(CommandArgument[2]);
}
switch (e.CommandName.ToLower())
{
case "view":
if (ProductID > 0 & SupplierID > 0 & CategoryID >
0)
{
ShowMessage(ProductID,
SupplierID, CategoryID);
}
break;
}
}
}
protected void
grvObject_RowDataBound(object sender, DatalistRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton cmdDetail = (ImageButton)e.Row.FindControl("cmdDetail");
if (cmdDetail != null)
{
cmdDetail.ToolTip = "View Details";
}
}
}
protected void
grvObject_PageIndexChanging(object sender,
System.Web.UI.WebControls.DatalistPageEventArgs
e)
{
grvObject.PageIndex = e.NewPageIndex;
BindProduct();
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindProduct();
}
}
catch
{
}
}
#endregion
}
}
VB.NET Code
'Visit http://laptrinhdotnet.com for
more ASP.NET Tutorials
Namespace MultipleArgumentsinCommandArgument
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Methods"
Private Sub
ShowMessage(ByVal ProductID As Integer, ByVal SupplierID As Integer, ByVal
CategoryID As Integer)
Dim sMessage As String = "ProductID:
" & ProductID & _
" - SupplierID: " & SupplierID &
_
" - CategoryID: " & CategoryID
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(),
"alert", "alert('"
& sMessage & "');", True)
End Sub
#End Region
#Region "Bind Data"
Private Sub
BindProduct()
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
updatePanel.Update()
Else
trMessage.Visible = True
grvObject.Visible = False
End If
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Select Products.* From Products")
Return objBind
End Function
#End Region
#Region "Datalist
Methods"
Private Sub
grvObject_RowCommand(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DatalistCommandEventArgs)
Handles grvObject.RowCommand
If (e.CommandName.ToLower <> "sort" And
e.CommandName.ToLower <> "page"
AndAlso e.CommandArgument.ToString <> "") Then
Dim CommandArgument() As String =
e.CommandArgument.ToString.Split(",")
Dim ProductID As
Integer = -1
Dim SupplierID As
Integer = -1
Dim CategoryID As
Integer = -1
If CommandArgument.Length > 0 Then
ProductID = CommandArgument(0)
SupplierID = CommandArgument(1)
CategoryID = CommandArgument(2)
End If
Select Case
e.CommandName.ToLower
Case "view"
If ProductID > 0 And SupplierID
> 0 And CategoryID > 0 Then
ShowMessage(ProductID, SupplierID, CategoryID)
End If
End Select
End If
End Sub
Private Sub
grvObject_RowDataBound(ByVal sender As Object, ByVal e As DatalistRowEventArgs) Handles
grvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow)
Then
Dim cmdDetail As
ImageButton = DirectCast(e.Row.FindControl("cmdDetail"), ImageButton)
If Not
cmdDetail Is Nothing
Then
cmdDetail.ToolTip = "View Details"
End If
End If
End Sub
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DatalistPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindProduct()
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
BindProduct()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project, và mỗi khi kích vào cột cuối cùng, một Popup sẽ xuất hiện hiển thị các giá trị của CommandArgument.
Chúc các bạn thành công!
Quang Bình
No Comment to " Sử dụng nhiều đối số trong CommandArgument trong Datalist "