在gridview中对标题进行分组

时间:2013-12-10 10:40:17

标签: asp.net listview gridview

参考此链接:http://www.4guysfromrolla.com/articles/091708-1.aspx 我想为gridview实现类似于下面列表视图中显示的分组标题。

HTML来源:

<asp:ListView ID="ProductsGroupedByDataField" runat="server" DataSourceID="odsAllPlannedLeaves"
   <LayoutTemplate>
      <table cellspacing="0" cellpadding="5" rules="all" border="1" >
         <tr style="background-color:#5D7B9D;color:White">
   <th>Start Date</th>
   <th>End Date</th>
   <th>Date Of Applying</th>
   </tr>
         <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
      </table>
   </LayoutTemplate>

   <ItemTemplate>
   <%# AddGroupingRowIfSupplierHasChanged() %>

      <tr class='data<%# Container.DataItemIndex % 2 %>'>
         <td><%#GetDate(Eval("Emp_StartDate"))%></td>
         <td><%#GetDate(Eval("Emp_EndDate"))%></td>
         <td><%#GetEntryDate(Eval("Emp_EntryDate"))%></td>

      </tr>
   </ItemTemplate>

</asp:ListView>

方法:

int LastEmpId = 0;
    protected string AddGroupingRowIfSupplierHasChanged()
    {
        int CurrentEmpId = Convert.ToInt32(Eval("Emp_Id").ToString());
        if (LastEmpId != CurrentEmpId)
        {
            LastEmpId = CurrentEmpId;
            string CurrentEmpName = Eval("Emp_Name").ToString();
            string CurrentEmailId = Eval("Emp_EmailID").ToString();
            return string.Format("<tr style='text-align:left' class='group'><td colspan='3'>Employee Name: " + CurrentEmpName + "&nbsp;&nbsp;|&nbsp;&nbsp;Email Id: " + CurrentEmailId + "</td></tr>");
        }
        else
            return string.Empty;
    }

如何在gridview中实现它?

1 个答案:

答案 0 :(得分:0)

我对Gridview的子标题使用了这个小“休息”:

private string tmpCategoryName = "";

protected void gdvRowDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
    HiddenField hdnTmpSubTitle = (HiddenField)e.Row.FindControl("hdnTmpSubTitle");

    if (!(tmpCategoryName == hdnTmpSubTitle.Value)) {

        tmpCategoryName = hdnTmpSubTitle.Value;
        Table tbl = e.Row.Parent as Table;
        if (tbl != null) {
            GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
            TableCell cell = new TableCell();

            cell.ColumnSpan = this.grdViewProjects.Columns.Count;
            cell.Width = Unit.Percentage(100);
            cell.Style.Add("font-weight", "bold");
            cell.Style.Add("background-color", "#c0c0c0");
            cell.Style.Add("color", "white");
            HtmlGenericControl span = new HtmlGenericControl("span");
            span.InnerHtml = tmpCategoryName;
            cell.Controls.Add(span);
            row.Cells.Add(cell);
            tbl.Rows.AddAt(tbl.Rows.Count - 1, row);

        }
    }
}

}

此代码获取位于Gridview内的顶级“类别”,只创建一个额外的表行,使用一个单元格,添加样式,然后添加类别名称。如果类别与行不同,则更改它。确保首先通过“类别”(或您作为副标题使用的任何内容)订购datasource

另外,请确保将HiddenField的“类别”放入Template Field的{​​{1}}。