1

目标:对于网格中的每一行,在其下渲染一行,跨越网格中的所有列。

原因:这样我们就可以在该行中嵌套网格,或者可以嵌套用于快速编辑的表单或更新面板。

挑战:在 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;
    }
}

替代文字

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

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

4

1 回答 1

0

尽可能快速和肮脏,但您可以考虑添加以下内容:

<asp:Literal ID="ltlExtraRow" runat="server">
</tr>
  <tr>
     <td colspan="9">x</td>
     <td colspan="8">y</td>
</asp:Literal>

在gridview的最后一列(itemtemplate)

于 2010-02-14T22:07:29.327 回答