P.C P.C - 2 months ago 6
C# Question

How do I turn a button_click event into a boolean function?

The outcome I'm looking for is to have a comboBox displaying a different list depending on the button clicked. Each button is tied to a different table and the comboBox is being used for all tables.

I've tried this suggestion:

private bool buttonClicked1 = false;
private void button1_Click(object sender, EventArgs e)
{
buttonClicked1 = true;
}
private bool buttonClicked2 = false;
private void button2_Click(object sender, EventArgs e)
{
buttonClicked2 = true;
}


private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (buttonClicked1 = true)
{
Run my code
}
Else
if (buttonClicked2 = true)
{
Run my code
}


The problem with the above code is that the logic gets stuck on the first "IF" statement (buttonClicked1 = true). Somehow the code memorizes the first click and sticks with it.

I'm kinda new to coding and I've searched for quite a while. Please take the time to ask me questions rather than quickly downvote just because you don't know the answer.

Thank you in advance!

P.S. Thank you for the answer. Not cool for the Jackass that downvoted the question...

Answer

One approach to handling this would be to create a single event handler that would accept all of your various click events and you could use the parameters for said event (sender and e) to resolve which button triggered the event :

// Store the button that was last clicked
private Button _lastClicked;

protected void GenericButton_Click(object sender, EventArgs e)
{
    // Resolve the button that was clicked
    var button = sender as Button;
    _lastClicked = button;
}

private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // Do something based off of the current button
    switch(_lastButton?.Name)
    {
         case "Button1":
            DoSomethingForButton1();
         break;
         case "Button2":
            DoSomethingForButton2();
         break;
         default:
            // Define your default event here (i.e. no button clicked)
            DoSomethingForButton1();
         break;
    }
}