I hit the brine using dynamic controls in the grid.
I bind gridview to the list and then add dyanmic controls. In order to maintain control state, I need to do this when the page loads. However, since events fire after the page loads, I cannot correctly handle sorting and swap events. Are there any creative solutions for this problem, or am I not mistaken about this?
EDIT: I'm not sure I correctly explained my problem. It doesn't matter where I add dynamic controls in the life cycle. The problem is that the sort and swap events require me to re-bind the GridView, which (apparently) causes the properties assigned to my dynamic controls to get lost from the ViewState, since the sort and search call bind occurs at the end of the life cycle.
protected void Page_Load(object sender, EventArgs e)
{
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";
lb.Command += new CommandEventHandler(AddItem);
lb.CommandName = "AddItem";
lb.CommandArgument = m.Model;
ph.Controls.Add(lb);
}
protected void grdProducts_OnSorting(object sender, GridViewSortEventArgs e)
{
hfSortExpression.Value = e.SortExpression.ToString();
grdProducts.PageIndex = 0;
}
source
share