Answer the question
In order to leave comments, you need to log in
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
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.
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);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question