简体   繁体   English

无法调用ASP.net中的按钮的功能

[英]Cant call function to button in ASP.net

I am adding textboxes and buttons programmatically, depending on the count of an array from the result of sql. 我以编程方式添加文本框和按钮,具体取决于sql结果中数组的数量。

I want to call a function(deleteButton_Click) for when each textbox change or when the delete button is pressed for each textbox. 我想为每个文本框更改或每个文本框按下删除按钮时调用一个函数(deleteButton_Click)。

When I press the button, the page reloads (I am using context handler to retrieve some data from a previous page) 当我按下按钮时,页面会重新加载(我正在使用上下文处理程序从上一页中检索一些数据)

here is a portion of my code, i can include the whole thing if needed. 这是我的代码的一部分,如果需要,我可以包括整个内容。 Ideas? 想法?

for(int i = 0; i < alMakers.Count; i++)
    {
        Label labLabel = new Label();
        labLabel.Text = "Lab" + (i + 1);

        labPanel.Controls.Add(labLabel);

        TextBox labs = new TextBox();
        labs.ID = "lab" + i;
        //labs.TextChanged += deleteLab;
        labPanel.Controls.Add(labs);
        labs.Text = labsList.GetValue(i).ToString();

        Button deleteButton = new Button();
        deleteButton.Text = "Delete";
        deleteButton.Click += deleteButton_Click;
        labPanel.Controls.Add(deleteButton);

        //form1.Controls.Add();


    }

here is a portion of my pageload from when I retreive the item from the previous page. 这是我上一页检索项目时页面加载的一部分。

protected void Page_Load(object sender, EventArgs e)
    {
        string studentID;
        if (!IsPostBack)
        {
            Page lastPage = (Page)Context.Handler;
            studentID = ((TextBox)lastPage.FindControl("editStudent")).Text;
            Label1.Text = studentID;

EDIT: My deleteButton_Click function (doesnt do anything as of yet, only changes the text of a label to "Hello") 编辑:我的deleteButton_Click函数(到目前为止尚未做任何事情,仅将标签的文本更改为“ Hello”)

protected void deleteButton_Click(object sender, EventArgs e)
    {
        Label2.Text = "Hello";
    }

In WebForms, control events such as a button click cause the page to completely reload. 在WebForms中,控件事件(例如按钮单击)会导致页面完全重新加载。 When that happens, you're starting over from scratch, and must recreate the buttons. 发生这种情况时,您将从头开始,必须重新创建按钮。 It sounds like you may have realized that much already. 听起来您可能已经意识到了很多。 Additionally, control events in ASP.Net Webforms rely on ViewState. 此外,ASP.Net Webforms中的控件事件依赖于ViewState。 By the time the Page_Load runs, the ViewState has already finished loading. 到Page_Load运行时,ViewState已经完成加载。 If you wait that long to recreate your buttons, it's too late to wire up the event handler for the button. 如果您等了很长时间才能重新创建按钮,那么为按钮连接事件处理程序为时已晚。

In order your click event to fire, you need to create your buttons at an earlier point in the page lifecycle , before the ViewState loads, such as Page_Init. 为了触发click事件,您需要在页面生命周期的较早位置创建按钮,然后再加载ViewState,例如Page_Init。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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