2

So i'm currently trying to get a simply cart working in a website. Basically, as the items are displayed from your cart on the cart page, a panel is populated with images, labels and buttons relating to each one.

What I want to do is assign a click event to every button created that calls a generic method to remove that item from the list. Here's the code for removing the item from the arraylist of items:

public void Remove(CartItem item)
{ 
    ArrayList remove = (ArrayList)Session["ShoppingBasket"];
    remove.Remove(item);
}

This is the event handler I'm trying to code for every button that's generated:

btnRemove.Click += new EventHandler(Remove(item));

For some reason, an error message is coming up saying that a method name is expected in the above line of code and I can't see where I'm going wrong. I'm not too familiar with using the EventHandler object so any guidance there would be greatly appreciated.

2 Answers 2

3

The EventHandler should match the signature of the Event. You can't just pass any method as an EventHandler. You need a proper void matching the signature of the event.

You can instead try a lambda expression:

btnRemove.Click += (_sender, _args) => Remove(item);

You could have used a separate method but since you need to pass the item to the function Remove, you need to use to use a lambda expression to be able to access item in the context.

Sign up to request clarification or add additional context in comments.

5 Comments

new EventHandler is redundant. Simplify it like this: btnRemove.Click += (s, e) => Remove(item);
@user2946329 Yes. I just copied it from the Original Post.
I've tried this method but now its having a problem with the EventArgs parameter. it says: "e cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter". Should I just use a different name for 'e'?
Oh, yes if you use this in another handler then you can just use a different name, it will work fine.
@Mark Consider accepting this answer so that future readers can find it useful too :)
0

Try this .

btnRemove.Click += (e,s)=> remove(item)

1 Comment

o yes, i just run IDE to check it syntactically while other posted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.