C# Checking if button was clicked

187,746

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}
Share:
187,746
ItsLuckies
Author by

ItsLuckies

Updated on March 23, 2020

Comments

  • ItsLuckies
    ItsLuckies about 4 years

    I am making a program that should just continue if 2 conditions are given.

    The first one, 2 TextBoxs have the same word in and a Button was clicked, which opens a new Form. Now I have the event for the "complete" button.

    private void button2_Click(object sender, EventArgs e)
    {
        if (textBox2.Text == textBox3.Text && ???) 
        {    
            StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
            myWriter.WriteLine(textBox1.Text);
            myWriter.WriteLine(textBox2.Text);
         }
    ]
    

    My problem is, I can't find a method that gives something like `button1.Clicked or something similar.

    I hope someone can help me here..

  • Yinda Yin
    Yinda Yin about 11 years
    Don't forget to reset the flag after you check it. Otherwise, it will only work once.
  • ItsLuckies
    ItsLuckies about 11 years
    Where do i have to fill in private bool button1WasClicked = false; ?
  • Jan Dörrenhaus
    Jan Dörrenhaus about 11 years
    Its a field inside your form class.
  • ItsLuckies
    ItsLuckies about 11 years
    What can i do if my system says that the acces was denied for creating the text file?
  • Jan Dörrenhaus
    Jan Dörrenhaus about 11 years
    Not store your text file under Program Files. That folder is specially protected in modern Windows versions :)
  • user3821206
    user3821206 over 8 years
    is this method applied if I have multiples Buttons??
  • Jan Dörrenhaus
    Jan Dörrenhaus over 8 years
    @user3821206 Sure, why not. Have one boolean flag for each button.