Click here to Skip to main content
15,891,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi.. All CodeProject Members
I download this code below from Microsoft Official Site
this Class Use For formatting textbox with numeric mask.
but i found some problem and need modified it
which it's can't accepted Minus (-) Character and i can't change the decimal digits into 4 decimal digits..
i have tried to modificated it hundred's time but still not find the
way..
Could anybody show me how the right code. then i can make the textbox
in Minus Format..and modified the decimal digits

thx for attn :
hope CodeProjects Better.. ^^

here is the code or you can download it at :
http://download.microsoft.com/download/0/8/7/087e6a47-7306-4a5c-ad97-d1ffd58d712e/DecimalTextBox.msi[^]
C#
static NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
/// <devdoc>
///     Overridden to validate and format the text.
/// </devdoc>
public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        if (value != base.Text)
        {
            SetFormattedText(new StringBuilder(value));
        }
    }
}
/// <devdoc>
///     Overridden to handle unsupported RETURN key.
/// </devdoc>
protected override bool IsInputKey(Keys keyData)
{
    if ((keyData & Keys.KeyCode) == Keys.Return)
    {
        return false;
    }
    return base.IsInputKey(keyData);
}

/// <devdoc>
///     Handle input filtering and text insertion.
/// </devdoc>
protected override void OnKeyPress( KeyPressEventArgs e )
{
    base.OnKeyPress( e );

    e.Handled = true;  // This disables undersired keys. ProcessCmdKey is used to enabled supported shortcuts.
    // Filter allowed input: integers or decimal separator only.
    if( !char.IsDigit( e.KeyChar ) && e.KeyChar != nfi.NumberDecimalSeparator[0] )
    {
        return;
    }
    int caretPos = this.SelectionStart;
    StringBuilder txt = new StringBuilder( this.Text );

    if (e.KeyChar == nfi.NumberDecimalSeparator[0])
    {
        // Go to decimal input location.
        this.SelectionStart = txt.Length - nfi.NumberDecimalDigits;
        return;
    }
    if( caretPos == txt.Length ) // caret at the end of the box
    {
        // input ignored.
        return;
    }
    int originalTextLength = txt.Length;
    if( originalTextLength - caretPos <= nfi.NumberDecimalDigits ) // caret at decimal location
    {
        // Replace the current location's value with the input.
        txt[caretPos] = e.KeyChar;
        this.Text = txt.ToString();
        this.SelectionStart = caretPos + 1;
    }
    else // caret at a whole number's location or at the decimal separator's location.
    {
        // If caret is at pos 0 and the number is zero, we need to move caret so it can be inserted after the 0
        // and get properly formatted; otherwise, the input would be inserted at zero (effect = multiplied by 10).
        if( caretPos == 0 && txt[0] == '0' )
        {
            caretPos++;
        }
        // Insert value.
        txt.Insert( caretPos, e.KeyChar );
        if( SetFormattedText( txt ) )
        {
            this.SelectionStart = caretPos + ( txt.Length - originalTextLength );
        }
    }
}

/// <devdoc>
/// </devdoc>
public override void ResetText()
{
    SetFormattedText(new StringBuilder("0"));
}
/// <devdoc>
///     Sets the decimal-formatted text into the control's text.
///     Returns false if an exception is thrown during text formatting due to overflow or unexpected characters in
///     the specified text.
///     Methods calling this method should check for the return value before doing further processing.
///     The input should contain interger numbers and decimal group separator characters only; it does not expect
///     the string to represent a well formatted decimal number.
/// </devdoc>
private bool SetFormattedText( StringBuilder txt )
{
    // Remove group separators to re-format the string.
    txt.Replace( nfi.NumberGroupSeparator, "" )
    try
    {
        double value = double.Parse( txt.ToString() ); // parse decimal value.
        txt.Length = 0; // clear text.
        txt.Append( value.ToString( "N", nfi ) ); // set new text.
        base.Text = txt.ToString(); // set control's text.
        return true;

    }
    catch( System.OverflowException )
    {
        // Input too big.
    }
    catch( System.FormatException )
    {
        Debug.Fail( "Input was not in a correct format." );
        // Input not formatted properly.
    }
    return false;
}

[removed the code that has nothing to do with your problem]
Posted
Updated 27-Oct-10 7:15am
v2

before coming to us, you should actually read through the code and see if you can't figure out what it's doing and how it's handling only allowing numbers and decimals.

You'd have seen a comment that says:
C#
// Filter allowed input: integers or decimal separator only.

So, after the comment, you would then need to figure out how to also allow minus signs.

Then, to limit the number of decimal digits, you would have to add your own code to check to see how many digits are already after the decimal. If there's more than 4, you would just disallow further entry.
 
Share this answer
 
it's easy to allow minus signs.
maybe i can figure like this
C#
protected override void OnKeyPress( KeyPressEventArgs e )
        {
            base.OnKeyPress( e );
string negativeS = NumberFormatInfo.CurrentInfo.NegativeSign;
            e.Handled = true;  // This disables undersired keys. ProcessCmdKey is used to enabled supported shortcuts.
            // Filter allowed input: integers or decimal separator only.
            if( !char.IsDigit( e.KeyChar ) && e.KeyChar != nfi.NumberDecimalSeparator[0] && e.Keychar.equals=negativeS)
            {
                return;
            }

.But there is a problem at
private bool SetFormattedText( StringBuilder txt )
it's make an error if we type the minus sign.
how about u try to allow the minus sign and try to recompile it....
and u will see my problem..
 
Share this answer
 
Comments
William Winner 27-Oct-10 16:14pm    
First, this:
e.Keychar.equals=negativeS
is not the way to allow minus signs. In fact that shouldn't even compile that way.
Second...while adding a line where you did to allow minus signs, doesn't handle it.
Someone could type "34.534-" and that's not a valid double so it will throw an error. You have to also handle the logic of what to do if the minus key is hit.
Third, don't post an update as an answer. Either update your original post, or add a comment to an answer that you're responding to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900