C# 关闭表单前保存更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1121213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:41:52  来源:igfitidea点击:

Form closing save changes before close

c#

提问by user95542

I have a Windows forms application in C# and I have a form that when the user closes it I ask, "do you want to save the changes"? How can I get the changes in my form? Here is some code:

我有一个 C# 中的 Windows 窗体应用程序,我有一个窗体,当用户关闭它时,我会问,“你想保存更改吗”?我怎样才能在我的表格中获得更改?这是一些代码:

public partial class DepartEdit : Form
{   
    string _nameDep; //This variavel get value textbox when form load

    {
        InitializeComponent();
    }
    private void DepartamentEdit_FormClosing(object sender, FormClosingEventArgs e)
    {


        if (txtNameDepart.Text != _nameDep && codDepartament > 0)//Here i compare
        {
            DialogResult dlg = MessageBox.Show("Save changes?", "Question", MessageBoxButtons.YesNo);

            if (dlg == DialogResult.Yes)
            {
                saveDepart(); // Metod save depart

                e.Cancel = false;

            }
            if(dlg ==DialogResult.No)
            {
                e.Cancel = false;

            }

        }        
}

There are a lot of textboxs and combo boxes? Is there any other way to get the changes in the form?

有很多文本框和组合框?有没有其他方法可以获得表单中的更改?

回答by ShdNx

Well I think the theory is good. There are some problems with the implementation.

嗯,我认为这个理论很好。实施中存在一些问题。

    if (dlg == DialogResult.Yes)
    {
        saveDepart(); // Metod save depart

        e.Cancel = false;

    }
    if(dlg ==DialogResult.No)
    {
        e.Cancel = false;

    }

I think it would be a lot similier to write this:

我认为写这个会更相似:

    if(dlg == DialogResult.Yes)
    {
          saveDepart();
    }
    // You don't need to change e.Cancel to false here unless you set it to true previously.

回答by bladefist

Loop the forms controls, and add your event watchers. These events will call a function in the form that will keep a Hashtable or some other various collection up to date w/ the status of any changes to a particular control.

循环表单控件,并添加您的事件观察者。这些事件将以这种形式调用一个函数,该函数将保持 Hashtable 或其他一些不同的集合与特定控件的任何更改的状态保持同步。

like I have, Hashtable changes;

像我一样,Hashtable 发生了变化;

then each time my event is called, i say, Add Control.Name, and then a change status, whatever you want. Then you have a list of controls that have been updated.

然后每次调用我的事件时,我说,添加 Control.Name,然后更改状态,无论您想要什么。然后您有一个已更新的控件列表。

I can go into more detail if need be, hopefully this will get you started.

如果需要,我可以详细介绍,希望这可以帮助您入门。

回答by sgmoore

A lot will depending on where the information is held.

很多将取决于信息的保存位置。

It you are using DataBinding you should be just monitoring the listChanged event or calling dataTable.GetChanges() if you are using a DataTable.

如果您使用的是 DataBinding,您应该只是监视 listChanged 事件或调用 dataTable.GetChanges()(如果您使用的是 DataTable)。

If the information comes from a class the implements ICloneable and IComparable, then you can take just take a backup copy when intialising the form (and after saving) and when closing you prepare you class for saving and compare it with the original.

如果信息来自实现 ICloneable 和 IComparable 的类,那么您可以在初始化表单时(以及保存后)和关闭时准备好保存类并将其与原始类进行比较。

Otherwise you can do something like

否则你可以做类似的事情

Declare a private variable

声明一个私有变量

 private bool requiresSaving =false;

Declare an event

声明一个事件

 private void SomethingChanged(object sender, EventArgs e)
 {
      requiresSaving  = true;
 }

Hook up this event to the various changed events, eg

将此事件连接到各种更改的事件,例如

 this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged);

(The actual event is sometimes called something different , eg ValueChanged, SelectedIndexChanged , but they can all point to SomethingChanged unless you need a particular event to do something else.)

(实际事件有时被称为不同的东西,例如 ValueChanged、SelectedIndexChanged,但它们都可以指向SomethingChanged,除非您需要特定事件来做其他事情。)

Check this variable when you are closing the form

关闭表单时检查此变量

private void DepartamentEdit_FormClosing(object sender, FormClosingEventArgs e)
{
    if (requiresSaving)
    {
      ....

You also need to set requiresSaving false in the saveDepart method.

您还需要在 saveDepart 方法中设置 requiresSaving false。

Alternatively I have seem code where, when the control is being intialised, the tag value is also set, and the formclosing event loops through each control and compares the original values (in the tag object) with the current values.

或者,我有一些代码,当控件被初始化时,标签值也被设置,并且表单关闭事件循环遍历每个控件并将原始值(在标签对象中)与当前值进行比较。

回答by Slotty

Create a string (or string[] I guess) within the Form_Load event and initialise them with the values present when the form first opens. eg

在 Form_Load 事件中创建一个字符串(或 string[] 我猜),并使用表单首次打开时存在的值初始化它们。例如

string oName = nameTextBox.Text;
string oCompany = companyComboBox.Text;

Then during the Form_Closing() event you can check these against the current values

然后在 Form_Closing() 事件期间,您可以根据当前值检查这些

private void Contact_FormClosing(object sender, FormClosingEventArgs e)
{
     if (oName!=nameTextBox.Text||oCompany!=companyComboBox.Text)
     {
         DialogResult result = MessageBox.Show("Would you like to save your changes",
             "Save?",
             MessageBoxButtons.YesNoCancel,
             MessageBoxIcon.Stop);
         if (result == DialogResult.Yes)
         {
             SaveFormValues();
         }
         else if (result == DialogResult.Cancel)
         {
             // Stop the closing and return to the form
             e.Cancel = true;
         }
         else
         {
             this.Close();
         }
     }
}