简体   繁体   中英

ASP.NET: EventHandler issue on Button object in Dictionary

I have 64 buttons on my page that represent a team (it's a sort of NCAA bracket type thing). The buttons on page load are stored into a Dictionary as a key. Team is an object that stores information about the team. On the initial page load, the event handlers are built, but when the page reloads after a submit by clicking one of the buttons, the handler disappears. When I tried to have it add them on every page load, I checked the handlers after they are added, and they're still not there anymore.

Is this an issue accessing the original object via the Dictionary?

I'm using it like this:

foreach (KeyValuePair<Button, Team> tb in TeamButtons){
    tb.Key.Click += new EventHandler(Tournament_Click);
}

Any ideas?

Page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<Team> teamlist;
        for (int i = 1; i < 5; i++)
        {
            using (Db db = new Db(ServerConnection.DEV))
            {
                using (SqlDataReader dr = db.GetData("SELECT A.TeamId, A.Description 'TeamName', A.Seed, A.RegionId, B.Quadrant, B.Description 'RegionName' " +
                                                    "FROM Team A JOIN Region B on B.RegionId = A.RegionId WHERE B.Quadrant=" + i.ToString()))
                {
                    teamlist = new List<Team>();
                    while (dr.Read())
                    {
                        teamlist.Add(new Team(
                            dr["TeamId"].ToString(),
                            dr["TeamName"].ToString(),
                            Convert.ToInt16(dr["Seed"]),
                            dr["RegionId"].ToString(),
                            dr["RegionName"].ToString(),
                            Convert.ToInt16(dr["Quadrant"])
                            ));
                    }
                    switch (i)
                    {
                        case 1: LoadButtons(Quad1, teamlist); break;
                        case 2: LoadButtons(Quad2, teamlist); break;
                        case 3: LoadButtons(Quad3, teamlist); break;
                        case 4: LoadButtons(Quad4, teamlist); break;
                    }
                }
            }
        }

        FFButtons = new Dictionary<Button, Team>();
        FTButtons = new Dictionary<Button, Team>();
        Winner = new Team();

        FFButtons.Add(btnQ1FFL, new Team());
        FFButtons.Add(btnQ2FFL, new Team());
        FFButtons.Add(btnQ3FFR, new Team());
        FFButtons.Add(btnQ4FFR, new Team());
        FTButtons.Add(btnLFT, new Team());
        FTButtons.Add(btnRFT, new Team());

        Session["TeamButtons"] = TeamButtons;
        Session["FFButtons"] = FFButtons;
        Session["FTButtons"] = FTButtons;
        Session["Winner"] = Winner;

        ResetWinners(64);
    }
    else
    {
        TeamButtons = (Dictionary<Button, Team>)Session["TeamButtons"];
        FFButtons = (Dictionary<Button, Team>)Session["FFButtons"];
        FTButtons = (Dictionary<Button, Team>)Session["FTButtons"];
        Winner = (Team)Session["Winner"];
    }

    LoadTeams();

}

Load Buttons:

private void LoadButtons(System.Web.UI.HtmlControls.HtmlTable table, List<Team> teamlist)
{
    int i = 0;
    foreach (System.Web.UI.HtmlControls.HtmlTableRow c in table.Rows)
    {
        foreach (System.Web.UI.HtmlControls.HtmlTableCell d in c.Cells)
        {
            foreach (Control f in d.Controls)
            {
                if (f is Button)
                {
                    TeamButtons.Add((Button)f, teamlist[i]);
                    i++;
                }
            }
        }
    }
}

LoadTeams:

private void LoadTeams()
{
    foreach (KeyValuePair<Button, Team> tb in TeamButtons)
    {
        tb.Key.Text = TeamText(tb.Value);
        switch (tb.Value.Quadrant)
        {
            case 1:
                tb.Key.Click += new EventHandler(Tournament1_Click);
                break;
            case 2:
                tb.Key.Click += new EventHandler(Tournament2_Click);
                break;
            case 3:
                tb.Key.Click += new EventHandler(Tournament3_Click);
                break;
            case 4:
                tb.Key.Click += new EventHandler(Tournament4_Click);
                break;
        }
    }
    foreach (KeyValuePair<Button, Team> tb in FFButtons)
    {
        tb.Key.Text = TeamText(tb.Value);
        if (tb.Value.Quadrant <= 2) tb.Key.Click += new EventHandler(TournamentFourL_Click);
        else tb.Key.Click += new EventHandler(TournamentFourR_Click);
    }
    foreach (KeyValuePair<Button, Team> tb in FTButtons)
    {
        tb.Key.Text = TeamText(tb.Value);
        tb.Key.Click += new EventHandler(TournamentTwo_Click);
    }
}

The handlers need to be added on every page cycle in the oninit method. Try that and see what happens. If that doesn't work, try posting some more complete page code. Also, if that doesn't work, can you specify how the buttons are created? Are they just present in the aspx or are they dynamically created? If they are dynamically created, make sure you assign an ID to each of them on creation.

The pages in ASP.NET are recreated every time a request is made, therefore all the dynamically added event handlers are lost with each new request. So as swannee already said, you need to add them in the OnInit method (OnLoad, Page_Load would work too) every time the page is requested. If you are interested in understanding the ASP.NET page life cycle better, check this page .

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