How to use dynamically created button event to redirect to another ASP.NET page?

Asked

Viewed 1,442 times

1

I’m trying to call the event the buttons that were created dynamically with a foreach

public void adicionarComanda()
{
    List<Comanda> lc = ControllerComanda.getComanda();

    foreach (Comanda comanda in lc)
    {
        Button bt = new Button();
        bt.Text = comanda.nome_Pessoa;
        bt.CssClass = "botoes";
        bt.Click += btnNome1_Click;
        bt.CommandArgument = comanda.nome_Pessoa;              

        HtmlGenericControl li = new HtmlGenericControl("li");
        li.Controls.Add(bt);
        ulBotoes.Controls.Add(li);
    }

}

And the event:

protected void btnNome1_Click(object sender, EventArgs e)
{
    string nomePessoa = (sender as Button).CommandArgument;
    Session["currentUser"] = nomePessoa.ToString();
    Response.Redirect("~/Mobile/Pages/produtosCategoria.aspx");
} 

How could I solve this problem and make the event work and I be redirected to the desired page? Thank you all so much!

  • Your system runs on the right Webforms ?

  • Yes Érik, it’s in webforms

  • 1

    Your code is correct, I just copied it, and managed to make it work correctly. In which event is calling the method adicionarComanda? It may be that a postback is occurring between creating your controls and clicking, causing them to miss the event. If you can, post the code that calls the method that creates the controls.

  • Hey, Marcus, what’s up? So, I use this button here to add a command to the database: protected void btnAdd_Click(Object Sender, Imageclickeventargs and) ' ConnectionComanda(name); txtName.Text = """; txtNome.Focus(); } protected void Page_load(Object Sender, Eventargs and) { addirComanda(); } And then on the Load page I call that add method command. But after I insert it, I have to re-load the page to show the buttons that were created.How would I insert and already appear?

  • Opa Marcus, I solved the problem! Just put a Reponse.Redirect() in the insert method commands to the current page, hence the buttons are generated! But thank you very much!

  • 1

    Put the solution here as an answer, it can help other people!

Show 1 more comment

1 answer

1

Events are called after Page_load, so the solution was in the event of adding the buttons put a Response.Redirect() to the same page in the event that adds the dynamic buttons.

protected void btnAdd_Click(object sender, ImageClickEventArgs e)
    {
        string nome = txtNome.Text.Trim();

        ControllerComanda.inserirComanda(nome);

        txtNome.Text = "";
        txtNome.Focus();

        Response.Redirect("~/Mobile/Pages/paginaComandas.aspx");
    }

Calling the same page after insertion will cause the page load to occur again and after that create the buttons.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.