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(" FormRow"));
newRow.Cells.Add(cell);
return newRow;
}
}
問題:的代碼異味是多一點點,比我將與此類似的代碼。我不喜歡我需要跟蹤最後一個數據行,因爲初級開發人員很難理解此代碼的迭代性質,以便進行維護。
問題:有沒有人知道在創建行後會調用什麼?該行何時實際添加到根表中,並且我可以重寫一個參與該表的方法。我已經用Reflector反編譯了GridView類,我只是看不到我在找什麼。