M
M
Maria2017-02-18 14:57:44
.NET
Maria, 2017-02-18 14:57:44

How to pass pressed button to another C# method?

Please tell me how to refer to the button that I pressed in the TakeMessage method, i.e. instead of btnTest, use the one that called the btnClick event handler.

public void TakeMessage(string btnStatus, string userName)
        {


            if (userName == "")
            {
                MessageBox.Show("Введите Ваше имя!");
            }

            else if (btnStatus == "Red")
            {
                btnTest.BackColor = Color.Green;
                btnTest.Text = "Свободно";
            }
            else
            {
                btnTest.BackColor = Color.Red;
                btnTest.Text = userName;
            }
        }

        
        private void btnClick(object sender, EventArgs e)
        {
            Control btn = (Control)sender;

            if (btn.BackColor == Color.Green)
            {
                btnStatus = "Green";
            }

            else
            {
                btnStatus = "Red";
            }

            Server.SendMessageToAll(btnStatus, tbLogin.Text);
            TakeMessage(btnStatus, tbLogin.Text);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (var button in Controls.OfType<Button>())
            {
                button.Click += btnClick;
            }
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey Shedko, 2017-02-18
@Mamboking

Use a delegate.

D
Dmitry Pavlov, 2017-02-18
@dmitry_pavlov

The sender parameter is the button that was pressed. Pass it as the third parameter to TakeMessage, after casting it to the button type, for example.

T
Tom Nolane, 2017-02-18
@tomnolane

public void TakeMessage(string btnStatus, string userName, Button btnTest)
        {


            if (userName == "")
            {
                MessageBox.Show("Введите Ваше имя!");
            }

            else if (btnStatus == "Red")
            {
                btnTest.BackColor = Color.Green;
                btnTest.Text = "Свободно";
            }
            else
            {
                btnTest.BackColor = Color.Red;
                btnTest.Text = userName;
            }
        }

private void btnClick(object sender, EventArgs e)
        {
            var btn = sender as Button; 

            if (btn.BackColor == Color.Green)
            {
                btnStatus = "Green";
            }

            else
            {
                btnStatus = "Red";
            }

            Server.SendMessageToAll(btnStatus, tbLogin.Text);
            TakeMessage(btnStatus, tbLogin.Text, btn);
        }

in your case, I see no reason to create a separate TakeMessage method ... everything that is in TakeMessage can be implemented in one handler method: btnClick

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question