简体   繁体   中英

ASP.NET LinkButton

I'm developing a user control (ascx) that loads LinkButton objects at runtime. When the aspx page is loaded in the Page_Load, the data source for each LinkButton is an entry of a Dictionary , for example ((ferrari, 2), (chevrolet, 10), (jeep, 6)) randomly ordered. When the user clicks the LinkButton to do PostBack to query the database with additional information about the item. But when the execution reaches the event:

protected void objHyperLink_Click (object sender, EventArgs e)

is no longer the same item that started the invocation of the event, is a different one. How do I get obtain the correct object that starts the event?

Thanks

Given the comment thread on your question, it sounds like you only want the random assignment to occur once in the page lifecycle and then prevent it from randomizing again before you handle the button click. You can do that by checking whether the page is posting back (which is what happens after you've clicked on one of the buttons and the server is going back through the page lifecycle before it gets to your click handler).

Icemanind suggested moving this work out of Page_Load , which is probably a good idea, but you will still need the same IsPostBack check.

public void Page_PreInit(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // create buttons
    }
}

public void Page_Init(object sender, EventArgs e)
{
    // The buttons exist, now assign events to them
}

I would suggest reading the infamous ASP.NET Page Life Cycle Overview MSDN article to better understand in which page events you should be performing certain actions.

Using excerpts from the above article, you can see why I used the above methods:

  • PreInit : "Create or re-create dynamic controls."
  • Init : "Use this event to read or initialize control properties."

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