使用可折叠/可扩展行创建 gridview C# asp.net
Posted
技术标签:
【中文标题】使用可折叠/可扩展行创建 gridview C# asp.net【英文标题】:Create gridview C# asp.net with Collapsable/Expandable Rows 【发布时间】:2017-12-14 02:34:51 【问题描述】:这是我数据库中的一个表。我想创建一个具有可折叠和可展开行的 Gridview。
StartDate EndDate Section_Name Section_Value
2017-06-27 2017-06-28 Section 1 pump1 300
2017-06-27 2017-06-28 Section 1 pump2 256
2017-06-27 2017-06-28 Section 1 pump3 11
2017-06-27 2017-06-28 Section 1 pump4 5252
2017-06-27 2017-06-28 Section 2 pump1 300
2017-06-27 2017-06-28 Section 2 pump2 256
2017-06-27 2017-06-28 Section 2 pump3 212
2017-06-27 2017-06-28 Section 3 pump1 1222
我希望它在网格视图中的外观:
(+-) SECTION 1 TOTAL: 5819
Section 1 pump1 300
Section 1 pump2 256
Section 1 pump3 11
Section 1 pump4 5252
(+-) SECTION 2 TOTAL: 786
Section 2 pump1 300
Section 2 pump2 256
Section 2 pump3 212 and so on...
如果您单击第 1 部分,它应该会显示第 1 部分下的所有内容,依此类推。
代码(javascript):
<script language="javascript" type="text/javascript">
$(document).ready(function ()
$('.ExpandCollapseStyle').click(function ()
var orderId = $(this).attr('alt');
if (!isDisplayed($('.ExpandCollapse' + orderId)))
$(this).attr('src', 'images/minus.gif');
$('.ExpandCollapse' + orderId).css("display", "block");
else
$(this).attr('src', 'images/plus.gif');
$('.ExpandCollapse' + orderId).css("display", "none");
)
$('.ExpandCollapseGrandStyle').click(function ()
$(".grdViewOrders tr").each(function ()
var orderId = $(this).find(".ExpandCollapseStyle").attr('alt');
if (orderId != 'undefined')
if ($(this).attr('alt') == 'Expanded')
$(this).find(".ExpandCollapseStyle").attr('src', 'images/minus.gif');
$('.ExpandCollapse' + orderId).css("display", "block");
$(this).attr('alt', 'Collapsed');
else
$(this).find(".ExpandCollapseStyle").attr('src', 'images/plus.gif');
$('.ExpandCollapse' + orderId).css("display", "none");
$(this).attr('alt', 'Expanded');
);
if ($('.ExpandCollapseGrandStyle').attr('alt') == 'Expanded')
$('.ExpandCollapseGrandStyle').attr('src', 'images/plus.gif');
$('.ExpandCollapseGrandStyle').attr('alt', 'Collapsed');
else
$('.ExpandCollapseGrandStyle').attr('src', 'images/minus.gif');
$('.ExpandCollapseGrandStyle').attr('alt', 'Expanded');
)
function isDisplayed(object)
// if the object is visible return true
if ($(object).css('display') == 'block')
return true;
// if the object is not visible return false
return false;
;
);
</script>
(网格视图)
<asp:GridView ID="grdViewOrders" BackColor="WhiteSmoke" runat="server" AutoGenerateColumns="False" CssClass="grdViewOrders"
GridLines="Vertical" ShowFooter="True" OnRowDataBound="grdViewOrders_RowDataBound"
onrowcreated="grdViewOrders_RowCreated" >
<Columns>
<asp:TemplateField HeaderText="Section Name" >
<ItemStyle Width="10px" />
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section Value">
<ItemStyle Width="10px" />
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="" DataField="Section_Name">
<HeaderStyle Width="150px" />
<ItemStyle Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="" DataField="Section_Value">
<HeaderStyle Width="150px" />
<ItemStyle Width="150px" />
</asp:BoundField>
</Columns>
<HeaderStyle Height="25px" Font-Bold="True" BackColor="DimGray" ForeColor="White"
HorizontalAlign="Center" VerticalAlign="Middle" />
<RowStyle Height="25px" BackColor="Gainsboro" HorizontalAlign="Center" VerticalAlign="Middle" />
<AlternatingRowStyle Height="25px" BackColor="LightGray" HorizontalAlign="Center"
VerticalAlign="Middle" />
<FooterStyle BackColor="Gray" />
</asp:GridView>
(C# 背后的代码)
public partial class Default3 : System.Web.UI.Page
// To keep track of the previous row Group Identifier
string strPreviousRowID = string.Empty;
// To keep track the Index of Group Total
int intSectionTotalIndex = 1;
string strGroupHeaderText = string.Empty;
double dblSectionTotal = 0;
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
Method();
protected void Method()
connection made to sql db and bind data to gv
protected void grdViewOrders_RowCreated(object sender, GridViewRowEventArgs e)
bool IsSectionTotalRowNeedtoAdd = false;
if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "Section_Name") == null))
IsSectionTotalRowNeedtoAdd = true;
intSectionTotalIndex = 0;
if (IsSectionTotalRowNeedtoAdd)
#region SectionTotal
GridView grdViewOrders = (GridView)sender;
// Creating a Row
GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);
//Adding Group Expand Collapse Cell
TableCell cell = new TableCell();
System.Web.UI.htmlControls.HtmlImage img = new System.Web.UI.HtmlControls.HtmlImage();
img.Src = "images/minus.gif";
img.Attributes.Add("class", "ExpandCollapseGrandStyle");
img.Attributes.Add("alt", "Expanded");
cell.Controls.Add(img);
cell.HorizontalAlign = HorizontalAlign.Left;
row.Cells.Add(cell);
//Adding Expand Collapse Cell
cell = new TableCell();
row.Cells.Add(cell);
//Adding Header Cell
cell = new TableCell();
cell.Text = "Section 1 Total";
cell.HorizontalAlign = HorizontalAlign.Left;
cell.ColumnSpan = 1;
row.Cells.Add(cell);
//Adding Amount Column
cell = new TableCell();
cell.HorizontalAlign = HorizontalAlign.Right;
row.Cells.Add(cell);
//Adding the Row at the RowIndex position in the Grid
grdViewOrders.Controls[0].Controls.AddAt(e.Row.RowIndex, row);
#endregion
protected void grdViewOrders_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
strPreviousRowID = DataBinder.Eval(e.Row.DataItem, "Section_Name").ToString();
double dblSAmount = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Section_Value").ToString());
dblSectionTotal += dblSAmount;
e.Row.Style.Add("display", "block");
e.Row.CssClass = "ExpandCollapse" + strPreviousRowID;
如果有更简单的方法,请留下链接或一些提示。谢谢。
为了进一步参考,我试图利用源代码: http://www.dotnettwitter.com/2012/07/group-total-and-grand-total-in-gridview_15.html
【问题讨论】:
对于这个问题,你必须使用Nested-GridView
而不是简单的GridView
或在DataList
中使用Gridview
@Asif.Ali 我不明白为什么?因为我只从一张表中获取数据?举个例子吧
【参考方案1】:
试试这个例子:
ASPX 代码:
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
<asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
</Columns>
.CS 代码
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
gvCustomers.DataSource = GetData("select top 10 * from Customers");
gvCustomers.DataBind();
private static DataTable GetData(string query)
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
using (SqlCommand cmd = new SqlCommand())
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
string customerId = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(string.Format("select top 3 * from Orders where CustomerId='0'", customerId));
gvOrders.DataBind();
使用 jQuery 和 JavaScript 的客户端展开折叠功能
对于子 GridViews 的展开和折叠,我使用了 jQuery
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("[src*=plus]").live("click", function ()
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
);
$("[src*=minus]").live("click", function ()
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
);
链接一:https://www.aspsnippets.com/Articles/Nested-GridView-Example-in-ASPNet-using-C-and-VBNet.aspx
链接2:http://www.c-sharpcorner.com/UploadFile/b926a6/nested-grid-view-in-Asp-Net/
【讨论】:
以上是关于使用可折叠/可扩展行创建 gridview C# asp.net的主要内容,如果未能解决你的问题,请参考以下文章
ASP.NET 使用带有展开/折叠功能的嵌套、可编辑 GridView 的 JQuery
如何使用 Angular 6 和 bootstrap 3.3.7 创建带有复选框列表的可折叠/可扩展/树结构