这是一个noob问题,但我试图使用一个字符串(myButton),它是根据调用该方法的按钮设置的,并尝试在参数内使用该字符串,但是我的IDE认为我直接使用了字符串。这是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GMA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string myButton;//Currently selected button
private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
{
myButton = "button1";
SoundRoute();
}
public void SoundRoute()
{
if ((myButton).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
{
SoundCall subForm = new SoundCall();
subForm.Show();
}
}
}
}
我很感激任何帮助。我知道我可以为每个按钮创建一个新按钮,但这对于学习目的和实际操作同样重要。我一直都在寻找答案,但没有运气。
答案 0 :(得分:3)
使用sender
参数并将其传递给您的SoundRoute
方法..这实际上是它的用途:
public void SoundRoute(object sender)
{
if (((Button)sender).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc.
{
SoundCall subForm = new SoundCall();
subForm.Show();
}
}
然后您的活动成为:
private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form
{
SoundRoute(sender);
}
然后,您可以进行单个事件,所有按钮都连接到(因为它"将被复制到表单上的所有按钮")。