Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Professionals,

I am designing a custom control which inherits from the TextBox class.

In this I have trapped the backspace and delete key in keypress event and at that point where the character is going to be removed I want to stuff a 'space' character into the textbox.

Please suggest suitable methods. Thanks in advance.
Posted
Updated 27-Jan-15 20:54pm
v2
Comments
CPallini 28-Jan-15 3:01am    
What is your doubt about? You know, you need to build a new string satisfying your requirement and assign it to the TextBox.Text property.
Priya-Kiko 28-Jan-15 3:13am    
Thank you for the response.

Yes, but I can build a new string accordingly, only if I know the position of the char removed.

You need to handle this event: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx[^], and keep track of the content of the textbox.
 
Share this answer
 
Here is a complete code of your problem.

C#
public partial class TrapDeleteBackSpaceTextBox : TextBox
{
    string m_TextBeforeTheChange;
    int m_CursorPosition = 0;
    bool m_BackPressed = false;
    bool m_DeletePressed = false;

    public TrapDeleteBackSpaceTextBox():base()
    {

    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        m_TextBeforeTheChange = this.Text;
        m_BackPressed = (e.KeyData == Keys.Back) ? true : false;
        m_DeletePressed = (e.KeyData == Keys.Delete) ? true : false;
        m_CursorPosition++;
        base.OnKeyDown(e);
    }
    protected override void OnTextChanged(EventArgs e)
    {
        this.SelectionStart = m_CursorPosition;
        base.OnTextChanged(e);
    }
    protected override void OnKeyUp(KeyEventArgs e)
    {
        if (m_BackPressed || m_DeletePressed)
        {
            this.Text = m_TextBeforeTheChange;
            this.Text = this.Text + " "; //I added Space you an add any charecter
        }
        base.OnKeyUp(e);
    }
}
 
Share this answer
 
Comments
Priya-Kiko 28-Jan-15 5:36am    
Thanks for your reply. I wanted to add the space in place of the deleted character and not as an extra character....
public partial class NumberBox : MaskedTextBox
{

    public NumberBox()
    {
        this.TextAlign = HorizontalAlignment.Right;
        this.Mask = "#####.##";
        this.PromptChar = ' ';
        this.KeyPress += NumberBox_KeyPress;
        this.KeyDown += NumberBox_KeyDown;
    }

    void NumberBox_KeyDown(object sender, KeyEventArgs e)
    {
        MaskedTextBox SenderTextBox = (MaskedTextBox)sender;
        if (e.KeyCode == Keys.Enter)
        {
            String NumberBoxMask = SenderTextBox.Mask;
            String NumberBoxText = SenderTextBox.Text;
            Int32 DecimalPointLocation = NumberBoxMask.IndexOf('.');

            /* Storing the Length of the mask
               before the decimal point location */
            Int32 IntegerLength = StrLeft(NumberBoxMask, DecimalPointLocation).Length;

            /* Storing the Length of the mask
               after the decimal point location */
            Int32 DecimalLength = StrRight(NumberBoxMask, NumberBoxMask.Length -  (DecimalPointLocation + 1)).Length;

            Double aDoubleNum = 0.00;

            /* Storing the integer part in a string.
               Even if all numbers are deleted in the
               integer part, we still get spaces
               to the extent of the integer part length atleast */
            String strInteger = NumberBoxText.Substring(0, IntegerLength);

            /* Storing the decimal part in a string.  If numbers are deleted from the
               decimal portion then an error occurs, hence applied this logic,
               though looks absurd, I accept ...
               (Better logic to handle this, Welcome) */

            String strDecimal = "".PadRight(DecimalLength, '0');
            for (int mi = DecimalLength; mi > 0; mi--)
            {
                try
                {
                    strDecimal = NumberBoxText.Substring(NumberBoxMask.Length - DecimalLength, mi);
                    break;
                }
                catch { }
            }

            /* Removing the spaces if any in
               between numbers in the integer part */
            for (int mi = 0; mi < strInteger.Length; mi++)
            {
                if (strInteger[mi] == ' ')
                    strInteger = strInteger.Remove(mi, 1);
            }

            /* Removing the spaces if any in
               between numbers in the decimal part */
            for (int mi = 0; mi < strDecimal.Length; mi++)
            {
                if (strDecimal[mi] == ' ')
                    strDecimal = strDecimal.Remove(mi, 1);
            }

            /* Arriving the finally formatted Double number. */

            String FormattedNum = "";
            FormattedNum = strInteger.Trim().PadLeft(IntegerLength, ' ') + "." + strDecimal.Trim().PadRight(DecimalLength, '0');
            SenderTextBox.Text = FormattedNum;

            // Just check if it is valid Double type digit
            try
            {
                aDoubleNum = Double.Parse(FormattedNum);
                e.Handled = true;
            }
            catch
            {
                MessageBox.Show("Invalid Value);
                e.Handled = false;
            }
        }
    }

    public void NumberBox_KeyPress(object sender, KeyPressEventArgs e)
    {
     /* This logic is as per suggestion from */ <a href="http://www.codeproject.com/Questions/869033/Please-guide-me-how-to-format-the-textbox-to-take?arn=0">Please guide me how to format the textbox to take input of double values.</a>[<a href="http://www.codeproject.com/Questions/869033/Please-guide-me-how-to-format-the-textbox-to-take?arn=0" target="_blank" title="New Window">^</a>]

        MaskedTextBox SenderTextBox = (MaskedTextBox)sender;
        if (e.KeyChar == '.')
        {
            Int32 PositionOfDecimalPoint = SenderTextBox.Text.IndexOf('.');
            PositionOfDecimalPoint++;
            SenderTextBox.SelectionStart = PositionOfDecimalPoint;
            SenderTextBox.SelectionLength = 0;
            e.Handled = true;
        }
    }

    private String StrLeft(String mstr, int mlen)
    {
        return mstr.Substring(0, mlen);
    }


    private String StrRight(String mstr, int mlen)
    {
        return mstr.Substring((mstr.Length - mlen), mlen);
    }
}
 
Share this answer
 
v2
Comments
Priya-Kiko 30-Jan-15 3:11am    
Please excuse any code in-discipline. I am still in the learning process.
This is not a commercially usable code, but can give idea to people looking for similar solution.

This code was intended to generate a textbox control with the similar functionality as a visual FoxPro textbox for numeric values especially.

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