开发者

Write Null/Nothing value with Databinding

I have extended a MaskedTextBox component to add some functionality. The text property of the extended MaskedTextBox is bound to a DateTime? property and the format of binding is set to a time format of "HH:mm:ss" (i.e. 24hr time). So that this masked text box will capture the display a time.

The extra functionality I have added is to make the component readonly unless the component is double clicked or the enter button is pressed (the back color of the control helps to inform the users if the component is locked/readonly or not). When the enter button is pressed I also suspend the bindings so that bound data is updated the users input won't be lost. The information is then written back to the value and databindings resumed when the user presses the enter key again.

This all works fine up to here, with values written and displayed as would be expected.

However, I also want to write the null or nothing value to the DateTime? property if the user hasn't entered any text (or invalid text but let's just stick with no text) when enter key is pressed to submit the new value.

Unlike with other valid entries in the MaskedTextBox, if I have no text entered when i execu开发者_如何学编程te:

        Me.DataBindings("Text").WriteValue()

(when 'locking' the MaskedTextBox) it then branches to the bound properties Get method as I step into each line of code in the debugger (as opposed to the Set method with other valid entries)

How can I write this null/nothing/"" value to the DateTime? property when no text "" is entered into the MaskedTextBox?

Thanks for the help!


In order to manipulate what value gets displayed in the bound control and saved in the bound property, you need to handle the Format and Parse events of the binding. See below a simplistic sample code:

maskedTextBox1.DataBindings.Add("Text", bindobj, "Time");
maskedTextBox1.DataBindings[0].Parse += new ConvertEventHandler(Form1_Parse);
maskedTextBox1.DataBindings[0].Format += new ConvertEventHandler(Form1_Format);

void Form1_Format(object sender, ConvertEventArgs e)
{
    if (e.Value == null)
        e.Value = "Null";
}
private void Form1_Parse(object sender, ConvertEventArgs e)
{
    DateTime d;

    if (DateTime.TryParse(e.Value.ToString(), out d))
        e.Value = d;
    else
        e.Value = null;
 }
private void maskedTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
        maskedTextBox1.DataBindings[0].WriteValue();
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜