2009-11-21 29 views
1

目标:对于网格中的每一行渲染下面的一行,该网格包含网格中的所有列。何时将ASP.NET GridView行实际添加到根表中?

为什么:这样我们可以在该行中嵌套网格,或者可以为表单快速编辑或更新面板。

挑战:在RowDataBound中,RowCreated您正在使用的行尚未添加到根表中。如果您想要在该行之前添加一行,您可以轻松地将e.row.parent控件转换为表格并将该行添加到该行,这样可以很容易。当你这样做时,它会显示在你正在使用的当前行之前。

例子:

protected void Page_Load(object sender, EventArgs e) 
{ 

    List<String> strings = new List<string>(); 
    strings.Add("Test1"); 
    strings.Add("Test2"); 
    strings.Add("Test3"); 

    CustomGridView GridView1 = new CustomGridView(); 
    GridView1.DataSource = strings.Select(s => new { Column1 = s }); 
    GridView1.DataBind(); 

    phGrid.Controls.Add(GridView1); 
} 

public class CustomGridView : GridView 
{ 
    public Table Table 
    { 
     get; 
     set; 
    } 

    public CustomGridView() 
    { 
     this.RowCreated += new GridViewRowEventHandler(CustomGridView_RowCreated); 
    } 

    protected override Table CreateChildTable() 
    { 
     Table = base.CreateChildTable(); 
     return Table; 
    } 

    GridViewRow lastRow; 
    void CustomGridView_RowCreated(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer) 
     { 
      if (lastRow != null) 
       this.Table.Rows.Add(CreateRow()); 

      lastRow = e.Row; 
     } 
    } 

    private static GridViewRow CreateRow() 
    { 
     GridViewRow newRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal); 

     TableCell cell = new TableCell(); 
     cell.Controls.Add(new LiteralControl("&nbsp;&nbsp;FormRow")); 

     newRow.Cells.Add(cell); 

     return newRow; 
    } 
} 

alt text

问题:的代码异味是多一点点,比我将与此类似的代码。我不喜欢我需要跟踪最后一个数据行,因为初级开发人员很难理解此代码的迭代性质,以便进行维护。

问题:有没有人知道在创建行后会调用什么?该行何时实际添加到根表中,并且我可以重写一个参与该表的方法。我已经用Reflector反编译了GridView类,我只是看不到我在找什么。

回答

0

快速和肮脏的可以,但你可以考虑添加类似:

<asp:Literal ID="ltlExtraRow" runat="server"> 
</tr> 
    <tr> 
    <td colspan="9">x</td> 
    <td colspan="8">y</td> 
</asp:Literal> 
在你的GridView的最后一列(ItemTemplate中)