开发者

Textbox related Question: Validating Like it was a DatagridView Cell

I need to validate a textbox as follows:

When the user changes focus from that textbox, I want to show the properly formated currency value, but without lost the real user-entered value, Because i need it for later Calculations, and if is the case, for later editing from the user...

Can i do that? i don't want to have another variable just for that, and i remmeber the "validating" (i think) event o开发者_Python百科n datagrid view that lets you keep the value and format that value, so if you have to change or use for calculations, you just use the VALUE property, and for showing, it uses the FORMATEDVALUE property... Can i do that?

Thanks!


Define a function which formats the user entered value and returns the formatted value. On the LostFocus event of the text box you can accept the value entered by the user and store it into a variable. Then, pass the variable value as a parameter to the function. Format your value and return the value to the textbox.

    private void textBox1_Leave(object sender, EventArgs e)
    {
        Int32 original_value = Convert.ToInt32(textBox1.Text);
        textBox1.Text = Format(original_value).ToString();
        //original_value still holds the value that the user entered.
        //textbox holds the formated value.

    }
    public int Format(int a)
    {
        //code to format your input value
        return a;
    }

This way your variable holds the acutal value entered by the user and the textbox will display the formatted value. Does this help.

If you do not want to use another variable at all then you can perhaps make your own class control that inherits the textbox control, or just get the source, and use the Override attribute for the class. this might help.


Why not simply have an event handler for the onblur event, which parses the string by removing all non-numeric (except the decimal point) characters and then converts to a decimal, then formats it as currency?

And then whenever you need the value, simply parse it again. There's no real need to keep what they've typed and the formatted value separate.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜