ASP.NET (C#) - 动态生成的 ImageButtons 的单击事件
在我的网站中,我生成了七个 ImageButtons,其中仅启用了一个(随机)。我想为该按钮生成一个单击事件,该事件仅在按下特定组合键时触发(例如:按 E+Click 时)。
感谢您的帮助。
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";
}
}
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 (e.g: 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";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要在 Page_Init 而不是 Page_Load 上添加按钮,因为在页面周期中注册事件的时间太晚了。
关于按下特定的组合键,我很确定您只能在客户端使用 Javascript 来完成此操作,抱歉我无法提供更多帮助。
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.