c# winform key press delete add 0

Booney 166 Reputation points
2021-10-03T00:04:11.44+00:00

Doing a bit of math if a user enters a number in a textbox and press delete or backspace textbox will show (0) zero instead of blank.
Any help appreciated.

 private void OnTextChanged(object sender, EventArgs e)
        {

            if (int.TryParse(txt_BackedOut.Text, out int i) && int.TryParse(txt_TOTAL.Text, out int j) && int.TryParse(txt_Online.Text, out int t))
                txt_Different.Text = (j - i - t).ToString();



            if (txt_Online.Text == "")
                MessageBox.Show("Please enter Zero or another number in the textbox");



        }
Developer technologies Windows Forms
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2021-10-04T02:51:33.62+00:00

    @Booney , I agree with the solution of vb2ae, you could try to use textbox.keyup event to get what you want.

    I make a sample code and you could have a look.

    Code:

     private void Form1_Load(object sender, EventArgs e)  
            {  
                textBox1.Text = "0";  
            }  
            private void textBox1_KeyUp(object sender, KeyEventArgs e)  
            {  
                if (e.KeyCode == Keys.Back&&textBox1.Text=="")  
                {  
                    textBox1.Text = "0";  
                }  
                if(!int.TryParse(textBox1.Text, out int i))  
                {  
                    MessageBox.Show("Please enter number and don't contain other character");  
                    textBox1.Text=textBox1.Text.Remove(textBox1.Text.Length - 1,1);  
                }  
            }  
       
    

    Result:

    137189-1.gif


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2021-10-03T10:38:31.837+00:00

    You should think about moving the code into the keyup or keypress event for the textbox. This will give you the keypressed so you can blank the textbox text if delete or backspace is pressed and value is 0

    https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keyup?view=net-5.0

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.