简体   繁体   中英

Dynamically generate buttons c # asp.net

Friends I have a question, I have a button to generate buttons, which generates 5 buttons dynamically and they have a click event that redirects me to a page, but when I click on the generated buttons it reloads the page and does nothing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace pruebastack
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btngenerar_Click(object sender, EventArgs e)
        {
            for(int i=1; i<=5; i++)
            {
                System.Web.UI.WebControls.Button Button1 = new System.Web.UI.WebControls.Button();
                Button1.Text = "boton" + i;
                Button1.Click += delegate
                {
                    Response.Redirect("https://www.udemy.com/courses/search/?p="+i+"&q=java");
                    
                };
                this.Panel1.Controls.Add(Button1);
            }
            
        }
    }
}

Will this work for you? I've checked, it works

protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 1; i <= 5; i++)
            {
                System.Web.UI.WebControls.Button Button2 = new System.Web.UI.WebControls.Button();
                Button2.Text = "boton" + i;
                Button2.UseSubmitBehavior = false;
                Button2.OnClientClick = $"return window.location.href = 'https://www.udemy.com/courses/search/?p={i}&q=java'";
                this.Panel1.Controls.Add(Button2);
            }
        }

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