什么时候ASP.NET GridView Rows实际上添加到根表?

时间:2009-11-21 16:16:14

标签: asp.net gridview add rows

目标:对于网格中的每一行,在其下方渲染一行,该行会扫描网格中的所有列。

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

挑战:在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类,我无法看到找到我要找的东西。

1 个答案:

答案 0 :(得分:0)

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

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

在gridview的最后一栏(itemtemplate)