Clicking on any of the dynamically generated button contr开发者_开发百科ols 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.
精彩评论