Windows Forms - get Text value from object of type button

后端 未结 3 1987
悲&欢浪女
悲&欢浪女 2021-01-15 04:24

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

相关标签:
3条回答
  • 2021-01-15 04:54
        private void HandleClick(object sender, EventArgs e)
        {
            var btn = sender as Button;
            if (btn != null)
            {
                MessageBox.Show(btn.Text);
            }
        }
    
    0 讨论(0)
  • 2021-01-15 05:00

    You need to cast sender to the Button class so you can access its properties:

    Button b = (Button)sender;
    MessageBox.Show(b.Text);
    
    0 讨论(0)
  • 2021-01-15 05:06

    One option is to cast the object to a Button, but rather than doing the casting you can change how the event handler is assigned so that you don't need to cast in the first place:

    foreach (var button in panel1.Controls.OfType<Button>())
    {
        button.Click += (_,args)=> HandleClick(button, args);
    }
    

    Then just change the signature of HandleClick to:

    private void HandleClick(Button button, EventArgs e);
    
    0 讨论(0)
提交回复
热议问题