(Show GridView Row Details in Modal Popup using Bootstrap) – Có rất nhiều cách để tạo Master Detail như sử dụng jQuery, AJAX ModalPopupExtender… Bài viết dưới đây sẽ hướng dẫn các bạn cách xây dựng chức năng Master Detail sử dụng Bootstrap trong Gridview. Trong danh sách là toàn bộ danh sách đơn hàng và khi kích vào nút Detail danh sách các sản phẩm trong đơn hàng đó sẽ xuất hiện.
- B1: Download CSDL Northwind tại đây và thực hiện công việc Restore Data.
- 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 UsingBootstrapDisplayGridViewRowDetails
{
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
}
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace UsingBootstrapDisplayGridViewRowDetails
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
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B3: Download thư viện Bootstrap, giải nén và copy file bootstrap.css vào thư mục Styles trong Project
- B4: Copy file bootstrap.js vào thư mục Js trong Project
- B5: Tạo thư mục UserControls và thêm file Popup_OrderDetails.ascx, mở file dưới dạng HTML và nhập thông tin phía dưới.
<%@ ControlLanguage="C#"AutoEventWireup="true"CodeBehind="Popup_OrderDetails.ascx.cs"Inherits="UsingBootstrapDisplayGridViewRowDetails.UserControls.Popup_OrderDetails"%>
<table width="100%" cellpadding="2" cellspacing="3">
<tr>
<td>
<asp:Label ID="lblItemID"Visible="false"runat="server"/>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="8"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyleCssClass="GridStyle_HeaderStyle"/>
<RowStyleCssClass="GridStyle_RowStyle"/>
<pagerstylecssclass="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="CategoryName">
<ItemStyle width="25%" />
<ItemTemplate>
<asp:Label ID="lblCategoryName"Text='<%# Eval("CategoryName") %>' 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="Quantity">
<ItemStyle HorizontalAlign="Right" width="8%" />
<ItemTemplate>
<asp:Label ID="lblQuantity"Text='<%# Eval("Quantity") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discount">
<ItemStyle HorizontalAlign="Right" width="8%" />
<ItemTemplate>
<asp:Label ID="lblDiscount"Text='<%# Eval("Discount") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>C# Code
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespaceUsingBootstrapDisplayGridViewRowDetails.UserControls
{
partial class Popup_OrderDetails : System.Web.UI.UserControl
{
#region"Private Members"
private int ItemID;
#endregion
#region"Bind Data"
public voidBindOrderDetail(int ItemID)
{
DataTable objBind = newDataTable();
objBind = BindData(ItemID);
if (ItemID != -1)
{
lblItemID.Text = ItemID.ToString();
}
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
grvObject.DataSource = objBind;
grvObject.DataBind();
grvObject.Visible = true;
}
else
{
grvObject.Visible = false;
}
}
}
private DataTableBindData(int ItemID)
{
SqlDataProvider objSQL = newSqlDataProvider();
DataTable objBind = objSQL.FillTable("SELECT [Order Details].ProductID, Products.ProductName, Products.CategoryID, Categories.CategoryName, [Order Details].UnitPrice,[Order Details].Quantity, [Order Details].Discount"+ " FROM Products INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID" + " Where [Order Details].OrderID=" + ItemID);
return objBind;
}
#endregion
#region"GridView Methods"
private voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgse)
{
grvObject.PageIndex = e.NewPageIndex;
if (!string.IsNullOrEmpty(lblItemID.Text))
{
ItemID =Convert.ToInt32(lblItemID.Text);
}
BindOrderDetail(ItemID);
}
#endregion
}
}VB.NET Code
NamespaceUsingBootstrapDisplayGridViewRowDetails.UserControls
Partial Class Popup_OrderDetails
Inherits System.Web.UI.UserControl
#Region "Private Members"
Private ItemID As Integer
#End Region
#Region "Bind Data"
Public SubBindOrderDetail(ByVal ItemID As Integer)
Dim objBind As New DataTable
objBind = BindData(ItemID)
If ItemID <> -1 Then
lblItemID.Text = ItemID
End If
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
grvObject.Visible = True
Else
grvObject.Visible = False
End If
End If
End Sub
Private FunctionBindData(ByVal ItemID AsInteger) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("SELECT [Order Details].ProductID, Products.ProductName, Products.CategoryID, Categories.CategoryName, [Order Details].UnitPrice,[Order Details].Quantity, [Order Details].Discount"& _
" FROM Products INNER JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID" & _
" Where [Order Details].OrderID="& ItemID)
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
If lblItemID.Text <> ""Then
ItemID = lblItemID.Text
End If
BindOrderDetail(ItemID)
End Sub
#End Region
End Class
- B7: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<head id="Head1" runat="server">
<title>Using Bootstrap to Display GridView Row Details in Modal Popup</title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Styles/GridStyle.css" rel="stylesheet" type="text/css" />
<link href="Styles/bootstrap.css" rel="stylesheet" type="text/css" />
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript' src="Js/bootstrap.js"></script>
</head>
- B8: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C# Code
<%@ PageTitle="Using Bootstrap to Display GridView Row Details in Modal Popup" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="UsingBootstrapDisplayGridViewRowDetails._Default"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="ListRecord"Src="~/UserControls/Popup_OrderDetails.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<div class="panel panel-default">
<div class="panel-heading">
<h3>Using Bootstrap to Display GridView Row Details in Modal Popup</h3>
</div>
<div class="panel-body">
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<tablecellpadding="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:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="10"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"OnRowCommand="grvObject_RowCommand"OnPageIndexChanging="grvObject_PageIndexChanging"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="OrderID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:TemplateField HeaderText="OrderDate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblOrderDate"runat="server"Text='<%# ((Eval("OrderDate") is DateTime) ? ((DateTime)Eval("OrderDate")).ToShortDateString() : Eval("OrderDate")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RequiredDate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblRequiredDate"runat="server"Text='<%# ((Eval("RequiredDate") is DateTime) ? ((DateTime)Eval("RequiredDate")).ToShortDateString() : Eval("RequiredDate")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShippedDate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblShippedDate"runat="server"Text='<%# ((Eval("ShippedDate") is DateTime) ? ((DateTime)Eval("ShippedDate")).ToShortDateString() : Eval("ShippedDate")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipName">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblShipName"Text='<%# Eval("ShipName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipAddress">
<ItemStyle width="22%" />
<ItemTemplate>
<asp:Label ID="lblShipAddress"Text='<%# Eval("ShipAddress") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center"width="2%"/>
<ItemTemplate>
<asp:LinkButton id="cmdDetail"runat="server"CssClass="btn btn-info" CausesValidation="False" CommandName="detail" CommandArgument='<%# Eval("OrderID") %>' text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1"runat="server">
<ProgressTemplate>
<imgsrc=""alt="Loading..."/>
</ProgressTemplate>
</asp:UpdateProgress>
<div id="detail" class="modal hide fade" tabindex=-1 role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-width="760">
<divclass="modal-header">
<buttontype="button"class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="myModalLabel">Detailed Order</h3>
</div>
<divclass="modal-body">
<asp:UpdatePanel ID="UpdatePanel2"runat="server">
<ContentTemplate>
<ModalPopup:ListRecord ID="ucOrderDetails"runat="server"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTriggerControlID="grvObject"EventName="RowCommand"/>
</Triggers>
</asp:UpdatePanel>
<divclass="modal-footer">
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</div>
</div>
</div>
</asp:Content>VB.NET Code
<%@ PageTitle="Using Bootstrap to Display GridView Row Details in Modal Popup" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="UsingBootstrapDisplayGridViewRowDetails._Default"%>
<%@ RegisterTagPrefix="ModalPopup"TagName="ListRecord"Src="~/UserControls/Popup_OrderDetails.ascx"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"runat="server">
</asp:ScriptManager>
<div class="panel panel-default">
<div class="panel-heading">
<h3>Using Bootstrap to Display GridView Row Details in Modal Popup</h3>
</div>
<div class="panel-body">
<asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
<ContentTemplate>
<tablecellpadding="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:GridView ID="grvObject"runat="server"AllowPaging="true"PageSize="10"
CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="OrderID"width="100%">
<AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle"/>
<RowStyle CssClass="GridStyle_RowStyle"/>
<pagerstyle cssclass="GridStyle_pagination"/>
<Columns>
<asp:TemplateField HeaderText="OrderDate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblOrderDate"Text='<%# Eval("OrderDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RequiredDate">
<ItemStyle HorizontalAlign="Center"width="8%"/>
<ItemTemplate>
<asp:Label ID="lblRequiredDate"Text='<%# Eval("RequiredDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShippedDate">
<ItemStyle HorizontalAlign="Center" width="8%" />
<ItemTemplate>
<asp:Label ID="lblShippedDate"Text='<%# Eval("ShippedDate").ToShortDateString %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipName">
<ItemStyle width="15%" />
<ItemTemplate>
<asp:Label ID="lblShipName"Text='<%# Eval("ShipName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ShipAddress">
<ItemStyle width="22%" />
<ItemTemplate>
<asp:Label ID="lblShipAddress" Text='<%# Eval("ShipAddress") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center"width="2%"/>
<ItemTemplate>
<asp:LinkButton id="cmdDetail"runat="server"CssClass="btn btn-info" CausesValidation="False" CommandName="detail" CommandArgument='<%# Eval("OrderID") %>' text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1"runat="server">
<ProgressTemplate>
<imgsrc=""alt="Loading..."/>
</ProgressTemplate>
</asp:UpdateProgress>
<div id="detail" class="modal hide fade" tabindex=-1 role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-width="760">
<divclass="modal-header">
<buttontype="button"class="close"data-dismiss="modal"aria-hidden="true">×</button>
<h3id="myModalLabel">Detailed Order</h3>
</div>
<divclass="modal-body">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<ModalPopup:ListRecord ID="ucOrderDetails"runat="server"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTriggerControlID="grvObject"EventName="RowCommand"/>
</Triggers>
</asp:UpdatePanel>
<divclass="modal-footer">
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
- B9: 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.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UsingBootstrapDisplayGridViewRowDetails
{
public partial class _Default : System.Web.UI.Page
{
#region"Bind Data"
private voidBindOrder()
{
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 Orders.* From Orders");
return objBind;
}
#endregion
#region"GridView Methods"
protected voidgrvObject_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgse)
{
intItemID = Convert.ToInt32(e.CommandArgument);
switch (e.CommandName.ToLower())
{
case "detail":
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append(" $('#detail').modal('show');");
sb.Append("</script>");
var ucDetails = (UsingBootstrapDisplayGridViewRowDetails.UserControls.Popup_OrderDetails)ucOrderDetails;
ucDetails.BindOrderDetail(ItemID);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ModalScript", sb.ToString(), false);
break;
}
}
protected voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgse)
{
grvObject.PageIndex = e.NewPageIndex;
BindOrder();
}
#endregion
#region"Event Handles"
protected voidPage_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
BindOrder();
}
}
catch
{
}
}
#endregion
}
}VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Namespace UsingBootstrapDisplayGridViewRowDetails
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private SubBindOrder()
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 Orders.* From Orders")
Return objBind
End Function
#End Region
#Region "GridView Methods"
Private SubgrvObject_RowCommand(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
Dim ItemID As Integer = Integer.Parse(e.CommandArgument)
Select Casee.CommandName.ToLower
Case "detail"
Dim sb AsNew System.Text.StringBuilder()
sb.Append("<script type='text/javascript'>")
sb.Append(" $('#detail').modal('show');")
sb.Append("</script>")
With CType(ucOrderDetails, UsingBootstrapDisplayGridViewRowDetails.UserControls.Popup_OrderDetails)
.BindOrderDetail(ItemID)
End With
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "ModalScript", sb.ToString(), False)
End Select
End Sub
Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindOrder()
End Sub
#End Region
#Region "Event Handles"
Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
Try
IfPage.IsPostBack = False Then
BindOrder()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment