JaredH20
JaredH20

Reputation: 368

How to add a count to a button click in a Winform

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();
}

Upvotes: 3

Views: 9527

Answers (4)

dimazaid
dimazaid

Reputation: 1671

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();
}

Upvotes: 1

yan.kun
yan.kun

Reputation: 6908

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.

Upvotes: 3

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.

Upvotes: 0

Ritch Melton
Ritch Melton

Reputation: 11598

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++;
       }
    }

Upvotes: 0

Related Questions