如何“一般地”检测点击事件? [英] How to "generally" detect click events?

查看:70
本文介绍了如何“一般地”检测点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 TableLayoutPanel 上有几个按钮,它们分配了某些标签以区分它们。

例如,如果一个按钮是蛋糕图标,那么它的标签是蛋糕,依此类推。



我想要实现的是,如果用户点击正确的按钮/项目,会有某种弹出消息,等等。



这是什么我到目前为止:



I have several buttons on a TableLayoutPanel that have certain tags assigned to them to distinguish them from one another.
Like for instance, if a button is a cake icon, then its tag is "cake", so on and so forth.

What I'm trying to achieve is that if the user clicks on the correct button/item, there will be some sort of a popup message, etc.

Here's what I have so far:

private void Buttons_Click(System.Object sender, System.EventArgs e)
        {
            Button btn = sender as Button;
            string tag = Convert.ToString(btn.Tag);

        //if the problem is cake, and the button has "cake" as its tag, then it's correct
            if (tag.Equals(problem))
            {
                //Add Score\
                MessageBox.Show("Correct!");
            }

            else
            {
                MessageBox.Show("Error");
                second -= 2;
            }
        }





但是消息框不会弹出。 (我不太确定这段代码,因为我在搜索可能的解决方案时遇到了这个问题)



The message boxes don't pop up though. (I'm not that sure of this code as I just ran across this while searching for a possible solution)

推荐答案

因为你没有得到任何MessageBox, if ... else的每一边都有一个,有两个明显的可能原因:

1)按钮Tag属性为null:你将在if语句中得到一个空引用异常对于空输入,Convert.ToString将返回null。 (无论如何我都会检查标准动作)

2)点击方法根本没有执行。



第二个是可能就是你要见面的人。因此,检查事件处理程序是否连接到每个Button.Click事件...因为我猜你没有那么做,而且它不是自动的。
Since you don't get any MessageBox, and there is one on each side of the if...else, there are two obvious possible causes:
1) The button Tag property is null: you will get a null reference exception on the if statement as Convert.ToString will return null for a null input. (I'd check as a standard action anyway)
2) The click method is not getting executed at all.

The second is probably the one you are meeting. So check that the event handler is hooked up to each and every Button.Click event...because I'm guessing you didn't do that bit, and it's not automatic.


这篇关于如何“一般地”检测点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆