Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取动态创建的按钮';单击它们时的名称?_C#_Winforms - Fatal编程技术网

C# 如何获取动态创建的按钮';单击它们时的名称?

C# 如何获取动态创建的按钮';单击它们时的名称?,c#,winforms,C#,Winforms,我正在做一个麻将游戏,我对C#完全是新手,我想知道当按钮被点击时,我怎么能记下它的名字。所有按钮都是在表单中动态创建的 public Button createButton(node x) { Button nButton; nButton = new Button(); nButton.Name = x.info.ToString(); nButton.Text = x.info.ToString();

我正在做一个麻将游戏,我对C#完全是新手,我想知道当按钮被点击时,我怎么能记下它的名字。所有按钮都是在表单中动态创建的

public Button createButton(node x)
    {
         Button nButton;
         nButton = new Button();
         nButton.Name = x.info.ToString();
         nButton.Text = x.info.ToString();
         nButton.Width = 55;
         nButton.Height = 75;
         nButton.Visible = true;
         if (x.isValid())
            nButton.Enabled = true;
         else
            nButton.Enabled = false;
         nButton.Click += new System.EventHandler(n1_click);
            return nButton;
    }
在表单中,我使用此代码获取按钮

myButton = createButton(tp);
myButton.Location = new System.Drawing.Point(25 , 25);
this.Controls.Add(myButton);

事件处理程序的第一个参数是发送方,您可以将其强制转换为按钮,然后访问Name属性

下面是事件处理程序的一个小示例

private void Button_Click(object sender, EventArgs e)
{
  Button button = sender as Button;
  if (button != null)
  {
     // Do something with button.Name
  }
}
编辑:正如Hans在评论中提到的,将
用作
可能会隐藏潜在的bug。在上面的例子中使用
as
操作符可以确保,如果您不小心将此处理程序连接到另一个控件的事件,代码将优雅地处理它,而不会抛出
InvalidCastException
,但也存在一个问题,因为现在它会自动失败,您可能不会发现代码中的错误。如果抛出异常,您会意识到存在问题,并能够找到它。所以更新后的代码应该是这样的

private void Button_Click(object sender, EventArgs e)
{
  // If sender is not a Button this will raise an exception
  Button button = (Button)sender;       

  // Do something with button.Name
}

使用下面的代码,您可以获得单击的按钮

    protected void Button1_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
    }

在处理单击“n1_click”的函数上

private void n1_click(object sender, EventArgs e)
{
     Button temp = (Button)sender;
     string neededText = temp.Text;
}

关于何时不使用as关键字的好例子。它隐藏着虫子。