Collection was modified enumeration operation may not execute in datalist - asp.net

I am getting error when i try to fire event after clicking button which is outside datalist.
Error shows in for each statement :
Collection was modified enumeration operation may not execute.
protected void btnSaveGrid_Click(object sender, EventArgs e)
{
foreach (DataListItem item in dlPl.Items)
{
CommandEventArgs commandArgs = new CommandEventArgs("SaveGrid", btnSaveGrid);
DataListCommandEventArgs repeaterArgs = new DataListCommandEventArgs(item,btnSaveGrid, commandArgs);
dlPl_ItemCommand(btnSaveGrid, repeaterArgs);
}
protected void dlPl_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "SaveGrid")
{
//Some work
}
}
can anyone help me?

You may not modify the collection while you are enumerating it. dlPl_ItemCommand modifies dlPl.Items, which is not allowed.If you move DataBind outside the loop, it should work.

Related

Why is my UserControl's ViewState partially saved?

I have a user control that makes substantial use of this.ViewState["Key"] = SomeValue. Most of it is loaded from my Page_Init():
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
}
}
The rest are set at various points.
But for some reason it's unavailable on subsequent postbacks. I overrode SaveViewState() to check, and only like three of them are saved!
protected override object SaveViewState()
{
List<object> viewStateObjectsBefore = ViewState.OfType<object>().ToList();
object ret = base.SaveViewState();
List<object> viewStateObjectsAfter = ViewState.OfType<object>().ToList();
GC.KeepAlive(viewStateObjectsBefore);
GC.KeepAlive(viewStateObjectsAfter);
GC.KeepAlive(ret);
return ret;
}
Both viewStateObjectsBefore and viewStateObjectsAfter contain 10 key/value pairs, but ret only contains three!
Added: Moving the initializations to Page_Load() is not an easily available option, because the initializations must be done before the parent's Page_Load() executes.
Adding a call to SetDirty() at the end of my Page_Init() solved the problem:
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
//Looks like the ViewState is not yet "tracking" changes before Page_Load.
//The items have to be marked as "dirty" manually so they'll be included by SaveViewState().
ViewState.SetDirty(true);
}
}

Select all items in listbox when updated via UpdatePanel

protected void Page_Load(object sender, EventArgs e)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (id == cboGroup.UniqueID)
{
foreach (ListItem i in lstTest.Items)
i.Selected = true;
}
}
}
This code runs when my cboGroup causes my UpdatePanel to refresh which has the lstTest in it and the data inside of it gets updated, but it does NOT select them all. How can I make it so when my UpdatePanel is finished refreshing all elements of the list box that it refreshed get selected?
[edit] I'm noticing now that at this point what's in the listbox is the previous values and not the new values I would need. So this seems to be before the listbox is filled with data (which is via a SqlDataSource) so it's probably overwriting this.
I was able to put my selection code in the list box's DataBound() event.
protected void lstTest_DataBound(object sender, EventArgs e)
{
SelectAllTest();
}

How to know the previous event handled in asp.net

on page load i have shown data from database onto a gridview(with edit and delete option). I also have a search button on the page. when i click on search the searched data should be visible in the gridview, which is working fine. But when i click on delete link after search it does not take the searched row. The page postsback after clicking on delete. I need to check the event performed prior to event performed on gridview. How to do that?? I hope that the issue is clear.. Any help is appreciated. Thanks.
Page_Load occurs before RowCommand, are you only binding grid if(!IsPostBack) ?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
BindGrid(searchText.Text);
}
protected void GridView_RowCommand(object sender, GridViewRowEventArgs e)
{
switch(e.CommandName)
{
case "Delete":
DeleteRow(e.Row.CommandArgument);
break;
}
}
private void BindGrid()
{
//GridView binding business logic.
}
private void BindGrid(String searchTerm)
{
//GridView binding logic with searchTerm.
}
private void DeleteRow(String commandArg)
{
//Convert command arg to ID or whatever and delete data.
}

How can I prevent the LinqDataSource Where clause from resetting on postback?

I'm trying to set the where clause on a LinqDataSource object bound to a GridView programmatically on a button click, but when the GridView rebinds data (for instance, when the user sorts) the Where clause resets back to the empty string. Is there a way to prevent this, or is there a better way to filter my results?
Perhaps you just add a ViewState property into your page/user control and then retrieve it on all post back?
public string MyLinqSourceWhere
{
get { return (string)this.ViewState["MyLinqSourceWhere"]; }
set { this.ViewState["MyLinqSourceWhere"] = value; }
}
public void Page_Load(object sender, EventArgs e)
{
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
public void Button1_Click(object sender, EventArgs e)
{
this.MyLinqSourceWhere = " .... ";
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
If that doesn't work, then perhaps bind on the LinqDataSource.Selecting event the fetch property from the viewstate to your where clause?? It all depends

Asp.net page - user control communication

I have a page Product.aspx,there I have a user control ProductDisplay.ascx which has been created by drag and drop.
Now when a button is clicked in ProductDisplay.ascx,I want a logging function to be called which is in Product.aspx.
To achieve this I have used delegates
on ProductDisplay.ascx
public delegate void LogUserActivity(ProductService objService);
public event LogUserActivity ActivityLog;
on Product.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
}
Now button click event of ProductDisplay.ascx
protected void imgBtnBuyNow_Click(object sender, ImageClickEventArgs e)
{
if (ActivityLog != null)
{
ActivityLog(Product);
}
Response.Redirect("~/User/ShoppingCart.aspx");
}
My problem is that whenever i click this button ActivityLog is null.Why is it null?
My idea is that once i click this button,page posts back and its previous state is lost.
Please help me out with a reason and solution.
Secondly,I want to do away with null checking
**if (ActivityLog != null)**
{
ActivityLog(Product);
}
I saw some code which instantiates a delegate with a default value the moment it is declared,but i was not able to find it.Please help.
I have found solution to first problem
if (!IsPostBack)
{
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
}
This was causing the issue.Move this line
ProductDisp.ActivityLog += new User_UserControl_ProductDisplayBox.LogUserActivity(LogProduct);
out of if (!IsPostBack)

Resources