3

I would like to know how I can add a counter to a button click event, for example, I would like to make it so that when you press the Save button it adds 1 to the counter. When the user presses Exit without saving anything I would like it to open my Save Changes form, I would need the count so I can put something along the lines of:

if(count ==0)
{
  frmExit search = new frmExit();
  search.ShowDialog();
}
1
  • 1
    A bool at the form level IsSaved = false then set this to true in the button click.. so pop up if its still false when exiting ! !
    – V4Vendetta
    Nov 15, 2011 at 11:16

4 Answers 4

3

It is as easy as that:

public class MyWindow {

   private int counter = 0;

   //Button click event
   private void mySaveButton_click(object sender, EventArgs e) {
      counter++;
   }
}

You could even use a boolean, as it doesn't seem that you need the information on how many times the button has been clicked.

1

Are you dealing with text? Do you edit more than once? Because you have to change its value to false again whenever edited ! If not this code will work just fine!

bool Save=false;

private void SaveButton_Click(object sender, EventArgs e)
{
  Save=true;
  ....
}

if(!Save)
{
  frmExit search = new frmExit();
  search.ShowDialog();
}
0

Add a member to the Form class called count:

 private int count;

Increment it in your OnClick handler:

    private void ExitButtonClick(object sender, EventArgs e)
    {
       if(count == 0)
       {
          frmExit search = new frmExit();
          search.ShowDialog();
          count++;
       }
    }
0

You can write some thing like

public bool SaveClicked{get; set;}

private void btnSave_Click(object sender, EventArgs e)
{
     try 
     {
         //do your stuff
     }
     catch(Exception ex)
     {

     }
     finally
     {
        SaveClicked = true;
     }
}

And in the exit button click you can write like

if(!SaveClicked)
{
  frmExit search = new frmExit(); 
  search.ShowDialog();
  SaveClicked = false; 
}     

Similarly you can do for count also, only thing is you need to reset it to 0 before the save.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.