c# - How to deal with control events firing when attempting to clear a form -


i'm looking efficient way clear winform after data has been submitted. use static method accepts control parameter , loops through control(s), determines type of control , clears contents of control. works quite problem i'm having control events. when clear control, control event fires , since there data type conversion present in event (int.parse example) causes error because once control cleared, control event fired , empty string passed int.parse. aside using bunch of if statements or int.tryparse in event control prevent data conversion happening, there better way clear control , not trigger it's event in process?

thanks

here example of control event , clear method:

    private void quantity_textchanged(object sender, eventargs e)     {         presenter.quantity = int.parse(quantity.text);     }  public static void clearform(control.controlcollection controls)     {         foreach (control ctrl in controls)         {             if (ctrl.gettype() == typeof(textbox))             {                 ((textbox)ctrl).text = "";             }              if (ctrl.gettype() == typeof(combobox))             {                 ((combobox)ctrl).selectedindex = 0;             }              if (ctrl.gettype() == typeof(datetimepicker))             {                 datetimepicker datepicker = ctrl datetimepicker;                 //datepicker.format = datetimepickerformat.custom;                 datepicker.customformat = "dd-mmm-yyyy";                 datepicker.value = datetime.today;             }              if (ctrl.haschildren)             {                 clearform(ctrl.controls);             }         }     } 

solution1 : need unwire eventhandlers subscribed control before clearing contents

and wire eventhandlers after clearing it.

solution 2:

you can return function before parsing integer if empty asbelow:

private void quantity_textchanged(object sender, eventargs e) {     if(string.isnullorwhitespace(quantity.text))         return;      presenter.quantity = int.parse(quantity.text); } 

solution 3: avoid exceptions invalid or empty values can use int.tryparse() method asbelow:

from msdn : int.tryparse()

converts string representation of number 32-bit signed integer equivalent. return value indicates whether conversion succeeded.

private void quantity_textchanged(object sender, eventargs e) {     int quantity;     if(int.tryparse(quantity.text,out quantity))       presenter.quantity = quantity.tostring(); } 

Comments

Popular posts from this blog

jQuery Mobile app not scrolling in Firefox -

c++ - How to add Crypto++ library to Qt project -

php array slice every 2th rule -