简体   繁体   中英

asp.net, c#, Image Button Event Handler

I have the following two image button event handlers in my code, for dynamically added image buttons, the first is called within the page load event and the event handler is firing (although I know I will need to move it out of the page load event), the second is called in the pre render event and the event handler is not firing when the button is clicked. Here is the code, the first (working):

protected void Page_Load(object sender, EventArgs e)
{
    // check if user logged in 
    if (Session["userID"] == null)
        Server.Transfer("login.aspx");

    else
    {
        try
        {
            // connect to db and get event info for user events
            using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UsersConnectionString1"].ConnectionString))
            {
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connection;
                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.CommandText = "GetUserEvents";
                    command.Parameters.AddWithValue("@UserID", Session["UserID"]);
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            //System.Diagnostics.Debug.Write(reader[1].ToString());

                            ImageButton anEvent = new ImageButton();
                            String eventid = reader[0].ToString();
                            anEvent.ImageUrl = "";
                            anEvent.Click += delegate(object sender2, ImageClickEventArgs e2) { anEvent_Click(sender, e, eventid); };

                            anEvent.ToolTip = (reader[1].ToString()) + "\n" + (reader[2].ToString()) + "\n" + (reader[3].ToString()) + "\n\n";

                            Panel3.Controls.Add(anEvent);
                            Panel3.Controls.Add(new LiteralControl("&nbsp &nbsp"));
                        }
                    }
                }
            }
        }

        catch (Exception ex)
        {
            //error handling...
        }
    }
}

protected void anEvent_Click(object sender, EventArgs e, string eventid)
{   
    // create session variable to identify event info for event page for specific event user clicks on
    Session["eventID"] = eventid;     
    Server.Transfer("Event.aspx");    
}

The second (not working):

protected override void OnPreRender(EventArgs e)
{
    UpdateNewsFeed();
    LoadUserEvents();
}


private void LoadUserEvents()
{
    try
    {
        // connect to db and get event info for user events
        using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UsersConnectionString1"].ConnectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.CommandText = "GetUserEvents";
                command.Parameters.AddWithValue("@UserID", Session["UserID"]);
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        //System.Diagnostics.Debug.Write(reader[1].ToString());

                        ImageButton anEvent = new ImageButton();
                        String eventid = reader[0].ToString();
                        anEvent.Click += delegate(object sender2, ImageClickEventArgs e2) { anEvent_Click(sender2, e2, eventid); };
                        anEvent.ImageUrl = reader[4].ToString();
                        anEvent.ToolTip = (reader[1].ToString()) + "\n" + (reader[2].ToString()) + "\n" + (reader[3].ToString()) + "\n\n";

                        EventsPanel.Controls.Add(anEvent);
                        EventsPanel.Controls.Add(new LiteralControl("&nbsp &nbsp"));
                    }
                }
            }
        }
    }

    catch (Exception ex)
    {
        //error handling...
    }
}

protected void anEvent_Click(object sender, EventArgs e, String eventid)
{
    Session["eventID"] = eventid;
    Server.Transfer("Event.aspx");
}

I'm assuming it's something to do with the object and the sender not being passed in correctly, but I don't know how to do this without having the method called in the page load event which I don't want to do as this means the buttons disappear on postback.

Any advice will be greatly appreciated, thanks all!

You are adding the controls too late (OnPreRender) in the page life cycle in the second example. . Try PreInit as MSDN recomend or Init or Load in the worse case you need to access to session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM