简体   繁体   中英

Asp.net: Page won't refresh after clicking dynamically generated Button controls

Clicking on any of the dynamically generated button controls does indeed call the b_Click method and delete the given user, however, upon deleting the page does not reload the 'new' list of users.

        protected void Page_Load(object sender, EventArgs e)
        {
          DbDB db = new DbDB();
          List<User> users = db.GetUsers().ExecuteTypedList<User>();

          foreach (User u in users)
          {
            Button b = new Button();
            b.Text = u.FirstName;
            b.Click += new EventHandler(b_Click);
            PlaceHolder1.Controls.Add(b);

          }

        }
       }

       void b_Click(object sender, EventArgs e)
       {

          Button b = (Button)sender;
          DbDB.User.Delete(x => x.FirstName == b.Text);

       }
protected void Page_Load(object sender, EventArgs e) {
   LoadUsers();
}

void b_Click(object sender, EventArgs e) {      
   Button button = (Button)sender;
   string firstName = button.CommandArgument;  
   DbDB.User.Delete(x => x.FirstName == firstName);

   PlaceHolder1.Controls.Remove(button);
}

void LoadUsers() {  
   DbDB db = new DbDB();
   List<User> users = db.GetUsers().ExecuteTypedList<User>();

   foreach (User user in Users) {
      Button button = new Button();         
      button.CommandArgument = user.FirstName;  // normally the user "id" to identify the user.
      button.Text = user.FirstName;
      button.Click += new EventHandler(b_Click);
      PlaceHolder1.Controls.Add(button);
   }
}

That's because the Page_Load event is called before the Click event so when you're retrieving the list of users from the database in Page_Load the user is still in there. As a quick solution you could move the code from Page_Load to PreRender event.

Have a look at this link for more info on the page life cycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx

You don't need to select users with every post-back. Also you don't need to create controls at runtime for this.

Following is an alternative way.

<asp:Repeater runat="server" ID="myRepeater">
    <ItemTemplate>
        <asp:Button runat="server" OnClick="Button_Click" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>' />
    </ItemTemplate>
</asp:Repeater>

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        // load users
        myRepeater.DataSource = users;
        myRepeater.DataBind();
    }
}

protected void Button_Click(object sender, EventArgs e)
{
    // delete user
    Button button = sender as Button;
    button.Visible = false;
}

Write your page_load body inside

if(!IsPostBack)
{
   ....
}

That should work.

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