2016-11-10 55 views
0

我目前正试图生成一个Gridview,它看起来像这样。以编程方式生成特定模板的gridview

Example

前两列与Boundfield,在那里我会抓住基于数据库中给出的数据来完成。

但是,问题出现时,我必须有行AM & PM

有没有办法为日期的标题做一个colspan,并创建一个行只为AM & PM?因为AM & PM不计为列,而是10/11/2016是列。

ASPX

<asp:GridView ID="gvAttendance" runat="server"> 
        <Columns> 
         <asp:BoundField DataField="traineeID" HeaderText="Trainee ID" /> 
         <asp:BoundField DataField="idNum" HeaderText="ID" /> 
        </Columns> 
       </asp:GridView> 

回答

0

这是可以做到,看看我的片段,并调整您的需求。片段将在默认标题中应用ColSpan,并向GridView添加额外的标题行。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     int spanColumn_1_start = 2; 
     int spanColumn_1_length = 2; 

     //apply colspan 
     e.Row.Cells[spanColumn_1_start].ColumnSpan = spanColumn_1_length; 

     //remove the spanned cells 
     for (int i = 1; i < spanColumn_1_length; i++) 
     { 
      e.Row.Cells.RemoveAt(spanColumn_1_start + 1); 
     } 

     //note that the startindex of the 2nd colspan is set after removing cells for 1st colspan 
     int spanColumn_2_start = 3; 
     int spanColumn_2_length = 2; 

     //apply colspan 
     e.Row.Cells[spanColumn_2_start].ColumnSpan = spanColumn_2_length; 

     //remove the spanned cells 
     for (int i = 1; i < spanColumn_2_length; i++) 
     { 
      e.Row.Cells.RemoveAt(spanColumn_2_start + 1); 
     } 
    } 
} 

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    //to add a row above the normal gridview header, use: if (e.Row.RowType == DataControlRowType.Header) 

    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItemIndex == 0) 
    { 
     //cast the sender as gridview 
     GridView gridView = sender as GridView; 

     //create a new gridviewrow 
     GridViewRow gridViewRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert); 

     //add some cells 
     TableCell tableCell = new TableCell(); 
     tableCell.Text = ""; 
     tableCell.ColumnSpan = 2; 
     gridViewRow.Cells.Add(tableCell); 

     tableCell = new TableCell(); 
     tableCell.Text = "AM"; 
     gridViewRow.Cells.Add(tableCell); 

     tableCell = new TableCell(); 
     tableCell.Text = "PM"; 
     gridViewRow.Cells.Add(tableCell); 

     tableCell = new TableCell(); 
     tableCell.Text = "AM"; 
     gridViewRow.Cells.Add(tableCell); 

     tableCell = new TableCell(); 
     tableCell.Text = "PM"; 
     gridViewRow.Cells.Add(tableCell); 

     //add the new row to the gridview 
     gridView.Controls[0].Controls.AddAt(1, gridViewRow); 
    } 
} 

结果会是这样

enter image description here

+0

对于'RowCreated',所以如果我有另一个另外3个日期?那么是否可以动态地添加'AM'' PM'? – Alvin

+0

无论如何,只想说感谢你的努力,我现在正在尝试代码。干杯。 (: – Alvin

+0

是的,只需在行中添加6个'TableCell'控件。 – VDWWD