I've gotten myself into a pickle with using dynamic controls in a gridivew.
I am binding the gridview to a list and am then adding dyanmic controls. IN order to keep the control state I need to do this in page load. However since events fire after page load I am unable to properly handle sorting and paging events. Are there any creative solutions to this problem or am I going about this all wrong?
EDIT: I am not sure I explained my problem correctly. It doesn't matter where I add the dynamic controls in the life cycle. The problem is that the sorting and paging events require me to rebind the GridView which (apparently) causes the properties assigned to my dynamic controls to be lost from ViewState since the binding on sorting and paging happens late in the life cycle.
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();
}