简体   繁体   中英

ASP.NET (C#) - click event for dynamically generated ImageButtons

in my website I'm generating seven ImageButtons from which only one (random) is enabled. I want to generate for that button a click event that is triggered only when a specific key combination is pressed (eg: when pressing E+Click).

Thanks for the help.

protected void Page_Load(object sender, EventArgs e)
    {
        //Generates a <int, string> dictionary
        LoginHelper.CreateDictionary(images);

        //'buttons' is an int list
        while (buttons.Count < 7)
        {
            //generates a random number from 1 to 7
            int number = LoginHelper.GenerateNumber();

            if (buttons.Contains(number) == false)
            {
                buttons.Add(number);
                ImageButton btn = new ImageButton();
                btn.CssClass = "loginButtons";
                btn.ImageUrl = (from x in images
                                where x.Key == number
                                select x.Value).First();
                //gets the link string according to the randomized number
                btn.PostBackUrl = LoginHelper.GetLink(number);

                if (btn.PostBackUrl == string.Empty)
                {
                    btn.Enabled = false;
                }

                btn.Click += new ImageClickEventHandler(btn_Click);

                footer.Controls.Add(btn);
            }
        }
    }
    //The event is not triggered
    void btn_Click(object sender, ImageClickEventArgs e)
    {
        ImageButton button = sender as ImageButton;
        ConsoleKeyInfo cki = Console.ReadKey();

        if (cki.Key == ConsoleKey.E)
        {
            button.PostBackUrl = "~/about.aspx";
        }
    }

first you'll need to add the buttons on the Page_Init rather than Page_Load, where it is to late in the page cycle for the event to be registered.

about the specific key combination is pressed, I'm pretty sure you'll only be able to accomplish this using Javascript on the client side, sorry I can't help more.

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