BindingSource Winforms to Business Object - Cannot leave text box

BindingSource Winforms to Business Object - Cannot leave text box

Post by RC1Tb21lb2 » Sat, 05 Jan 2008 02:12:02


I'm binding a text box to a Integer (Nullable) property of a business object.
If the user enters invalid data or even enteres nothing (example, just
leaves it blank) they cannot leave the field at all. Adding an ErrorProvider
gives me "Invalid Cast Exception" as the error. How can I allow the user to
leave the text box even if there is bad data in it? This is definatly not
desired functionality for me. I've tried putting code in the Validating and
LostFocs events and still have not had any luck. There are good reasons why
a user would not want to enter data into one of the bound text boxes and when
this occurs I'd like the business object property to be set to a value of
nothing/null. I;'ve tried that in code to by manually setting the BO
property to Nothing but the user still cannot exit the combo box.

What do I need to do to allow myself to bind a text box to a business object
and not have the user stuck in that text box if they erase the existing value
and put in no data (aka:empty string). Simply they need to be able to leave
the box and the databinding needs to accept the empty string returned from
the text box as a null/nothing value.

D.
 
 
 

BindingSource Winforms to Business Object - Cannot leave text box

Post by TW9ydGVuIF » Sat, 05 Jan 2008 20:43:02

Hi D,

Try handling the Format and Parse events of the Binding object. Inside
these events you can convert control types to business. The code snippet
below should work with any text input, passing null for all non number values.

protected override void OnLoad(EventArgs e)
{
TextBox tb = new TextBox();
Controls.Add(tb);

MyClass mc = new MyClass();

Binding b = new Binding("Text", mc, "Value", true);
b.Parse += new ConvertEventHandler(b_Parse);
b.Format += new ConvertEventHandler(b_Format);
tb.DataBindings.Add(b);
}

void b_Format(object sender, ConvertEventArgs e)
{
int? value = e.Value as int?;
e.Value = null;
if (value != null)
e.Value = value.ToString();
}

void b_Parse(object sender, ConvertEventArgs e)
{
string s = e.Value as string;
int value = 0;
if (int.TryParse(s, out value))
e.Value = value;
else
e.Value = null;
}

class MyClass
{
private int? _value;

public int? Value
{
get { return _value; }
set { _value = value; }
}
}



--
Happy Coding!
Morten Wennevik [C# MVP]