views:

226

answers:

1

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.

A: 

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)

Rohit