(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 stringConnectionString
{
get { return_connectionString; }
}
#endregion
#region"Functions"
public DataTableFillTable(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(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; }
}
}
}
Imports System.Data.SqlClient
Imports System.Data
Namespace MultipleArgumentsinCommandArgument
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 sql AsString) As DataTable
Try
Dim tb AsNew DataTable
Dim adap AsNew 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 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
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#
<%@ PageTitle="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%">
<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: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">
<AlternatingRowStyleCssClass="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
<%@ PageTitle="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%">
<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:Datalist ID="grvObject" runat="server" AllowPaging="true" PageSize="12"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="ProductID"width="100%">
<AlternatingRowStyleCssClass="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 voidShowMessage(int ProductID, int SupplierID, intCategoryID)
{
string sMessage = "ProductID: " + ProductID + " - SupplierID: " + SupplierID + " - CategoryID: " + CategoryID;
ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('"+ sMessage + "');", true);
}
#endregion
#region"Bind Data"
private voidBindProduct()
{
DataTable objBind = newDataTable();
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 DataTableBindData()
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("Select Products.* From Products");
return objBind;
}
#endregion
#region "Datalist Methods"
protected voidgrvObject_RowCommand(object sender, System.Web.UI.WebControls.DatalistCommandEventArgse)
{
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 voidgrvObject_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 voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.DatalistPageEventArgse)
{
grvObject.PageIndex = e.NewPageIndex;
BindProduct();
}
#endregion
#region"Event Handles"
protected voidPage_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 SubShowMessage(ByVal ProductID As Integer, ByVal SupplierID As Integer, ByValCategoryID 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 SubBindProduct()
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 FunctionBindData() 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 SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.DatalistCommandEventArgs) Handles grvObject.RowCommand
If (e.CommandName.ToLower <> "sort" Ande.CommandName.ToLower <> "page"AndAlso e.CommandArgument.ToString <> "") Then
Dim CommandArgument() As String = e.CommandArgument.ToString.Split(",")
Dim ProductID AsInteger = -1
Dim SupplierID AsInteger = -1
Dim CategoryID AsInteger = -1
If CommandArgument.Length > 0 Then
ProductID = CommandArgument(0)
SupplierID = CommandArgument(1)
CategoryID = CommandArgument(2)
End If
Select Casee.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 SubgrvObject_RowDataBound(ByVal sender As Object, ByVal e As DatalistRowEventArgs) HandlesgrvObject.RowDataBound
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim cmdDetail AsImageButton = DirectCast(e.Row.FindControl("cmdDetail"), ImageButton)
If NotcmdDetail Is NothingThen
cmdDetail.ToolTip = "View Details"
End If
End If
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.DatalistPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindProduct()
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
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
0 comments Blogger 0 Facebook
Post a Comment