且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows窗体 - 从类型的按钮对象获取的文本值

更新时间:2023-12-06 11:37:16

 私人无效HandleClick(对象发件人,EventArgs五)
{
VAR BTN =发件人的按钮;
如果(BTN!= NULL)
{
MessageBox.Show(btn.Text);
}
}


I have a Windows form named Form1 and panel within this form named panel1. I use the panel only to place buttons there so that I can group them and work with them separately from the other buttons in my Form1. For the purpose of my program I need to handle every button click made from the buttons inside panel1. For this purpose I use the same code snippet:

  public Form1()
        {
            InitializeComponent();

            // Set a click event handler for the button in the panel
            foreach (var button in panel1.Controls.OfType<Button>())
            {

                button.Click += HandleClick;
            }
        }

What I need to do is to have a way to identify which button exactly has been clicked. For this purpose I played a little bit with my handler method:

private void HandleClick(object o, EventArgs e)
{
    MessageBox.Show("HI" + o.ToString());
}

which gave me some hope because I get this:

It's the second part - Text: button4 which is actually enough information to continue with my work. But I can't find a way to get this piece of information without some complicated string manipulations. So is there a way to get this or other unique information about the button been clicked given the way I have written my code?

    private void HandleClick(object sender, EventArgs e)
    {
        var btn = sender as Button;
        if (btn != null)
        {
            MessageBox.Show(btn.Text);
        }
    }