Reputation: 526
I am looking for a way to display other data in a MaskedTextBox than the data it is bound to (DataTable).
More specifically: The DataTable contains a DateTime column (DateOfBirth). Whenever the year is 1900, I would like to display it as empty in the MaskedTextBox while keeping it in the underlying DataTable, because I use 1900 for "unknown".
Example: Value in the DataTable: 1900-10-09 --[DataBinding]--> MaskedTextBox __-10-09
Currently, I am using the CurrentItemChanged-Event of the BindingSource, to modify the Text-property of the MaskedTextBox. That works nicely as long as I simply browse through the DataTable. However, as soon as I start editing the MaskedTextBox, 1900 is back.
It would be nicer if I could somehow intercept the value that is passed from the DataRow to the MaskedTextBox, instead of replacing it afterwards.
Or maybe there is a way to get the MaskedTextBox to display 1900 as empty?
Upvotes: 0
Views: 1966
Reputation: 369
For completeness: Solution at codeproject
Have you tried Binding::Format and Binding::Parse? http://msdn.microsoft.com/en-US/library/system.windows.forms.binding_members(v=vs.80).aspx
Upvotes: 1
Reputation: 526
As Catalin pointed out, using the Binding.Format event did the trick:
Binding mtbGebdatBinding = mtbGebdat.DataBindings.Add("Text", _bsPerson, (string)mtbGebdat.Tag, true);
mtbGebdatBinding.Format += new ConvertEventHandler(mtbGebdatBinding_Format);
void mtbGebdatBinding_Format(object sender, ConvertEventArgs e)
{
if (DBNull.Value != e.Value)
{
string date = String.Format("{0:dd/MM/yyyy}", (DateTime)e.Value);
if (date.Substring(6, 4) == "1900")
{
e.Value = date.Substring(0, 6);
}
}
}
Upvotes: 1
Reputation: 3212
I think that you need a ValueConverter. Create a class derived form IValueConverter and use it in your binding.
Upvotes: 0