Winforms databinding and validation, why is datasource updated when validation fails? -
the code below illustrates unexpected (for me!) behaviour when combining data binding , validation in winforms. can tell me how can prevent datasource being updated when validation fails?
many thanks.
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; namespace validationbug { /// <summary> /// illustrates unexpected behaviour winforms validation , binding /// /// reproduce: run program, enter value textbox, click x close form. /// /// expected behaviour: validation of textbox fails data source not updated. /// /// observed behaviour: data source updated. /// </summary> public class form1 : form { private class data { private string _field; public string field { { return _field; } set { // should never called, is. _field = value; } } } private system.componentmodel.icontainer components = null; public form1() { this.load += new system.eventhandler(this.form1_load); } private void form1_load(object sender, eventargs e) { autovalidate = system.windows.forms.autovalidate.enablepreventfocuschange; var txt = new textbox(); // validation fails. txt.validating += new canceleventhandler((s, ev) => ev.cancel = true); controls.add(txt); var data = new data(); this.components = new system.componentmodel.container(); bindingsource bs = new bindingsource(this.components); bs.datasource = typeof(data); // update datasource on succesful validation. txt.databindings.add(new binding("text", data, "field", false, datasourceupdatemode.onvalidation)); } } }
i tend "brute force" code - set initial value private string _field
, perhaps in constructor?
also, sure setting canceleventhandler
's cancel property true marks data invalid?
you may want add private bool _valid
field data class returns values if valid.
private class data { private bool _valid; private string _field; public data() { _field = null; _valid = false; } public string field { { if (_valid) { return _field; } else { return null; } set { // should never called, is. _field = value; _valid = !string.isnullorempty(_field); } } }
just ideas into.
Comments
Post a Comment