简体   繁体   English

如何在Winform中单击按钮添加计数

[英]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. 我想知道如何为按钮点击事件添加一个计数器,例如,我想这样做,当你按下Save按钮时,它会向计数器添加1。 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: 当用户按下Exit而不保存任何我希望它打开我的保存更改表单时,我需要计数,所以我可以放置以下内容:

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

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. 您甚至可以使用boolean ,因为您似乎不需要有关按钮被单击的次数的信息。

Are you dealing with text? 你在处理文字吗? Do you edit more than once? 你不止一次编辑? Because you have to change its value to false again whenever edited ! 因为每次编辑都必须再次将其值更改为false! 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();
}

Add a member to the Form class called count: 将一个成员添加到名为count的Form类中:

 private int count;

Increment it in your OnClick handler: 在OnClick处理程序中增加它:

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

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. 类似地,你也可以为count做,只需要在保存之前将它重置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM