ASP.NET GridView的第二个标题行跨越主标题行

问题描述 投票:32回答:8

我有有看起来像这样的列的ASP.NET的GridView:

| Foo | Bar | Total1 | Total2 | Total3 |

是否有可能创建两行,看起来像这样一个标题?

|           |  Totals   |    
| Foo | Bar | 1 | 2 | 3 |

每一行中的数据将保持不变,因为这仅仅是漂亮了头,并且电网占用降低了水平空间。

整个GridView控件是在重要的情况下,排序。我不打算为添加的“总计”栏跨越有任何排序功能。

编辑:

基于以下给出的物品中的一个,我创建从GridView的继承和在将第二标题行的类。

namespace CustomControls
{
    public class TwoHeadedGridView : GridView
    {
        protected Table InnerTable
        {
            get
            {
                if (this.HasControls())
                {
                    return (Table)this.Controls[0];
                }

                return null;
            }
        }

        protected override void OnDataBound(EventArgs e)
        {
            base.OnDataBound(e);
            this.CreateSecondHeader();
        }

        private void CreateSecondHeader()
        {
            GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);

            TableCell left = new TableHeaderCell();
            left.ColumnSpan = 3;
            row.Cells.Add(left);

            TableCell totals = new TableHeaderCell();
            totals.ColumnSpan = this.Columns.Count - 3;
            totals.Text = "Totals";
            row.Cells.Add(totals);

            this.InnerTable.Rows.AddAt(0, row);
        }
    }
}

如果你是新的ASP.NET像我,我也应该指出的是,您需要:

1)加入这样一行到您的Web表单注册类:

<%@ Register TagPrefix="foo" NameSpace="CustomControls" Assembly="__code"%>

2)更改ASP:GridView控件在以前标记为foo:TwoHeadedGridView。不要忘了关闭标签。

另一个编辑:

你也可以做到这一点,而无需创建一个自定义类。

只需添加一个事件处理程序为网格这样的DataBound事件:

protected void gvOrganisms_DataBound(object sender, EventArgs e)
{
    GridView grid = sender as GridView;

    if (grid != null)
    {
        GridViewRow row = new GridViewRow(0, -1,
            DataControlRowType.Header, DataControlRowState.Normal);

        TableCell left = new TableHeaderCell();
        left.ColumnSpan = 3;
        row.Cells.Add(left);

        TableCell totals = new TableHeaderCell();
        totals.ColumnSpan = grid.Columns.Count - 3;
        totals.Text = "Totals";
        row.Cells.Add(totals);

        Table t = grid.Controls[0] as Table;
        if (t != null)
        {
            t.Rows.AddAt(0, row);
        }
    }
}

自定义控件的好处是,你可以看到你的web表单的设计视图中的额外的标题行。该事件处理方法有点简单,不过。

c# asp.net gridview
8个回答
11
投票

This article应该指向你在正确的方向。您可以以编程方式创建行和它在位置0添加到集合。


10
投票

我把接受的答案的方法,但所附加的标题到现有的GridView,而不是继承GridView的自定义。

我结合我的GridView控件之后,我做到以下几点:

/*Create header row above generated header row*/

//create row    
GridViewRow row = new GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal);

//spanned cell that will span the columns I don't want to give the additional header 
TableCell left = new TableHeaderCell();
left.ColumnSpan = 6;
row.Cells.Add(left);

//spanned cell that will span the columns i want to give the additional header
TableCell totals = new TableHeaderCell();
totals.ColumnSpan = myGridView.Columns.Count - 3;
totals.Text = "Additional Header";
row.Cells.Add(totals);

//Add the new row to the gridview as the master header row
//A table is the only Control (index[0]) in a GridView
((Table)myGridView.Controls[0]).Rows.AddAt(0, row);

/*fin*/

2
投票

注意:对于那些谁选择使用的RowDataBound方法在VB.NET

如果你结束了太多额外的标题行弹出,添加一个声明,如果只有在GridView的标题行是没有进入(这意味着它是目前正在绑定的一个)

 If grid.HeaderRow Is Nothing Then

1
投票

你将不得不创建延伸GridView控件,然后重写CreateRow方法的类。

尝试this为出发点


1
投票

添加t.EnableViewState = false;您添加的行后:

Dim t As Table = TryCast(grid.Controls(0), Table)
If t IsNot Nothing Then
    t.Rows.AddAt(0, row)
End If

t.EnableViewState = false;

0
投票

请参考https://stackoverflow.com/a/9333714/1060656

我创建这个溶液例如

要在您的本地系统运行将需要创建2个文件(一个用于控制和一个ASPX),则可以做一个项目或2个项目。

  1. GridViewPlus ==>控制类
  2. GridViewPlusCustomHeaderRows ==>收集保存自定义标题类
  3. CustomHeaderEventArgs ==>创建自定义标题行,当事件参数
  4. aspx文件==>测试程序 public class GridViewPlus : GridView { public event EventHandler<CustomHeaderEventArgs> CustomHeaderTableCellCreated; private GridViewPlusCustomHeaderRows _rows; public GridViewPlus() : base () { _rows = new GridViewPlusCustomHeaderRows(); } /// <summary> /// Allow Custom Headers /// </summary> public bool ShowCustomHeader { get; set; } [PersistenceMode(PersistenceMode.InnerDefaultProperty)] [MergableProperty(false)] public GridViewPlusCustomHeaderRows CustomHeaderRows { get {return _rows; } } protected virtual void OnCustomHeaderTableCellCreated(CustomHeaderEventArgs e) { EventHandler<CustomHeaderEventArgs> handler = CustomHeaderTableCellCreated; // Event will be null if there are no subscribers if (handler != null) { // Use the () operator to raise the event. handler(this, e); } } protected override void OnRowCreated(GridViewRowEventArgs e) { if (ShowCustomHeader && e.Row.RowType == DataControlRowType.Header) return; base.OnRowCreated(e); } protected override void PrepareControlHierarchy() { //Do not show the Gridview header if show custom header is ON if (ShowCustomHeader) this.ShowHeader = false; base.PrepareControlHierarchy(); //Safety Check if (this.Controls.Count == 0) return; bool controlStyleCreated = this.ControlStyleCreated; Table table = (Table)this.Controls[0]; int j = 0; if (CustomHeaderRows ==null )return ; foreach (TableRow tr in CustomHeaderRows) { OnCustomHeaderTableCellCreated(new CustomHeaderEventArgs(tr,j)); table.Rows.AddAt(j, tr); tr.ApplyStyle(this.HeaderStyle); j++; } } } public class GridViewPlusCustomHeaderRows : System.Collections.CollectionBase { public GridViewPlusCustomHeaderRows() { } public void Add(TableRow aGridViewCustomRow) { List.Add(aGridViewCustomRow); } public void Remove(int index) { // Check to see if there is a widget at the supplied index. if (index > Count - 1 || index < 0) // If no widget exists, a messagebox is shown and the operation // is cancelled. { throw (new Exception("Index not valid")); } else { List.RemoveAt(index); } } public TableRow Item(int Index) { // The appropriate item is retrieved from the List object and // explicitly cast to the Widget type, then returned to the // caller. return (TableRow)List[Index]; } } public class CustomHeaderEventArgs : EventArgs { public CustomHeaderEventArgs(TableRow tr ,int RowNumber ) { tRow = tr; _rownumber = RowNumber; } private TableRow tRow; private int _rownumber = 0; public int RowNumber { get { return _rownumber; } } public TableRow HeaderRow { get { return tRow; } set { tRow = value; } } } public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Example1(); GridViewExtension1.CustomHeaderTableCellCreated += new EventHandler<CustomHeaderEventArgs>(GridViewExtension1_CustomHeaderTableCellCreated); } void GridViewExtension1_CustomHeaderTableCellCreated(object sender, CustomHeaderEventArgs e) { TableRow tc = (TableRow)e.HeaderRow; tc.BackColor = System.Drawing.Color.AliceBlue; } private void Example1() { System.Data.DataTable dtSample = new DataTable(); DataColumn dc1 = new DataColumn("Column1",typeof(string)); DataColumn dc2 = new DataColumn("Column2",typeof(string)); DataColumn dc3 = new DataColumn("Column3",typeof(string)); DataColumn dc4 = new DataColumn("Column4",typeof(string)); // DataColumn dc5 = new DataColumn("Column5",typeof(string)); dtSample.Columns.Add(dc1); dtSample.Columns.Add(dc2); dtSample.Columns.Add(dc3); dtSample.Columns.Add(dc4); // dtSample.Columns.Add(dc5); dtSample.AcceptChanges(); for (int i = 0; i < 25; i++) { DataRow dr = dtSample.NewRow(); for (int j = 0; j < dtSample.Columns.Count; j++) { dr[j] = j; } dtSample.Rows.Add(dr); } dtSample.AcceptChanges(); //GridViewExtension1.ShowHeader = false; GridViewExtension1.ShowCustomHeader = true; /* *======================================================================= * |Row 1 Cell 1 | Row 1 Col 2 (Span=2) | Row 1 Col 3 | * | | | | *======================================================================= * |Row 2 Cell 1 | | | | * | | Row 2 Col 2 | Row 2 Col 3 |Row 2 Col 4 | *======================================================================= * * * * * */ // SO we have to make 2 header row as shown above TableRow TR1 = new TableRow(); TableCell tcR1C1 = new TableCell(); tcR1C1.Text = "Row 1 Cell 1"; tcR1C1.ColumnSpan = 1; TR1.Cells.Add(tcR1C1); TableCell tcR1C2 = new TableCell(); tcR1C2.Text = "Row 1 Cell 2"; tcR1C2.ColumnSpan = 2; TR1.Cells.Add(tcR1C2); TableCell tcR1C3 = new TableCell(); tcR1C3.Text = "Row 1 Cell 3"; tcR1C3.ColumnSpan = 1; TR1.Cells.Add(tcR1C3); GridViewExtension1.CustomHeaderRows.Add(TR1); TableRow TR2 = new TableRow(); TableCell tcR2C1 = new TableCell(); tcR2C1.Text = "Row 2 Cell 1"; tcR2C1.ColumnSpan = 1; TR2.Cells.Add(tcR2C1); TableCell tcR2C2 = new TableCell(); tcR2C2.Text = "Row 2 Cell 2"; tcR2C2.ColumnSpan = 1; TR2.Cells.Add(tcR2C2); TableCell tcR2C3 = new TableCell(); tcR2C3.Text = "Row 2 Cell 3"; tcR2C3.ColumnSpan = 1; TR2.Cells.Add(tcR2C3); TableCell tcR2C4 = new TableCell(); tcR2C4.Text = "Row 2 Cell 4"; tcR2C4.ColumnSpan = 1; TR2.Cells.Add(tcR2C4); GridViewExtension1.CustomHeaderRows.Add(TR2); GridViewExtension1.DataSource = dtSample; GridViewExtension1.DataBind(); } }

0
投票

我想做一个类似的任务,但需要点击按钮的水箱内 - 无在这种情况下,担任事件处理程序没有有线了上述的(由于事件的顺序)。最后,我使用的HeaderTemplate中标记在网格视图的适当模板列。在HTML看起来有点更加臃肿,但事件仍然与背后的努力没有额外的代码。例如

<asp:TemplateField >
             <HeaderTemplate>
               <div>
                <div style="text-align: center;padding-bottom: 5px;">
                                                          text
                   </div>
                    <div>
                     <asp:Button ID="Button1" runat="server" Text="Apply to all" ToolTip="Apply to all - Special Bolt On" CssClass="sub_button input_btn_5" OnClick="ApplyButton1_Click" />
                   </div>
                  </div>
                  </HeaderTemplate>
                  <ItemTemplate>....
© www.soinside.com 2019 - 2024. All rights reserved.