我已經把自己變成了一個在網格中使用動態控件的泡菜。Gridview分類和分頁動態生成控件
我將gridview綁定到列表,然後添加dyanmic控件。爲了保持控制狀態,我需要在頁面加載中做到這一點。然而,因爲事件在頁面加載後觸發,我無法正確處理排序和分頁事件。有什麼創造性的解決方案來解決這個問題嗎?或者我對這一切都有錯?
編輯:我不知道我解釋我的問題是否正確。在生命週期中添加動態控件的位置並不重要。問題在於排序和分頁事件要求我重新綁定GridView,這顯然會導致分配給我的動態控件的屬性在ViewState中丟失,因爲排序和分頁的綁定發生在生命週期的後期。
protected void Page_Load(object sender, EventArgs e)
{
//NOTE: to maintain control state of dynamic controls all databinding needs to be done in page load.
grdProducts.DataSource = GetDataSource();
grdProducts.DataBind();
}
protected void grdProducts_OnRowDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow) return;
ManufacturerProduct m = new ManufacturerProduct();
m.Model = DataBinder.Eval(e.Row.DataItem, "Model").ToString();
PlaceHolder ph = new PlaceHolder();
ph = (PlaceHolder)e.Row.FindControl("phAddToCart");
LinkButton lb = new LinkButton();
lb.Text = "Add To Cart";
//NOTE: if I bind after page load the command never fires.
lb.Command += new CommandEventHandler(AddItem);
lb.CommandName = "AddItem";
lb.CommandArgument = m.Model;
ph.Controls.Add(lb);
}
protected void grdProducts_OnSorting(object sender, GridViewSortEventArgs e)
{
//NOTE: since events fire after page load I can't handle this properly.
hfSortExpression.Value = e.SortExpression.ToString();
grdProducts.PageIndex = 0;
//NOTE: If I rebind here I hose my dynamic controls
//grdProducts.DataSource = GetDataSource();
//grdProducts.DataBind();
}
檢查此線程,它可能給你的想法http://stackoverflow.com/questions/5947780/how-to-convert-a-gridview-to-datatable-and-sort-the-datatable/5947912#5947912 – 2011-05-17 16:42:31