开发者

checking if form data has been changed

I have 开发者_JS百科been trying the following C# code to check if form data has been changed before closing and saving but it seems that it always reports the form as being changed even when no changes were made.

//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); 


//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.


I think you hook up these events even before you load your initial data. Then SomethingChanged fires and enable the save button even the user doesn't change anything.

You could either unhook these events when loading the default/existing data or hook up these events after loading default/existing data.

//Un-Hook when loading your default/existing data.
 private void SetDefaultData()
 {
     this.txtNameDepart.TextChanged -= new System.EventHandler(this.SomethingChanged); 
     this.txtNameDepart = "My default text";
     this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged); 
 }


you should show all the places where you set the flag to true, just in case.

also this code:

//Hook up this event to the various changed events, eg
 this.txtNameDepart.TextChanged += new System.EventHandler(this.SomethingChanged)

even understanding what you are trying to do, I think this is bad because if you have many controls and soon or later you will handle the logic of each change event with some more specific code for the individual controls, you should not attach the same event handler to all of them at once.

if all your controls are bound to a BindingSource you could use another approach.

if your controls are populated manually by you with some assignment from a business object on form load, you could also imagine to compare such object's properties with the original one (if you also saved a copy of the original of course) in the form_closing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜