C# Calculator

Hemanth B 886 Reputation points
2021-05-22T12:59:23.963+00:00

Hi, I created a Calculator using Visual Studio C#. I added a backspace button for making it more convenient for users. But once I coded the button (Refer the image below for the code) and tested it did not work as expected. Example: When I tested by typing "543" number in textbox and pressed the backspace button, it erased the number "3" from "543" and the result was only "54" but when I pressed another number after backspacing for example "9", the number "3" appeared again resulting the output "5439". The "3" did not get erased. Please help!98787-screenshot.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2021-05-23T10:41:27.7+00:00

    For .NET Framework

    public static class Extensions
    {
    
        public static string TrimLastCharacter(this string sender) => 
            string.IsNullOrWhiteSpace(sender) ? 
                sender : 
                sender.TrimEnd(sender[sender.Length - 1]);
    }
    

    For .NET Framework Core 5 (Here note the ^1 which targets the last character in the string ^ is know as a hat.

    public static class Extensions
    {
        public static string TrimLastCharacter(this string sender) => 
            string.IsNullOrWhiteSpace(sender) ? 
                sender : 
                sender.TrimEnd(sender[^1]);
    }
    

    How to use

    textBox1.Text = textBox1.Text.TrimLastCharacter();
    
    0 comments No comments

  2. Timon Yang-MSFT 9,586 Reputation points
    2021-05-24T06:00:00.927+00:00

    I used your code to test but did not encounter the problem you mentioned.

            private void button1_Click(object sender, EventArgs e)  
            {  
                if (textBox1.Text.Length>0)  
                {  
                    textBox1.Text = textBox1.Text.Remove(lastCharPosi, 1);  
                }  
                if (textBox1.Text=="")  
                {  
                    textBox1.Text = "0";  
                }  
                MessageBox.Show(textBox1.Text);  
            }  
      
            private int lastCharPosi;  
            private void textBox1_TextChanged(object sender, EventArgs e)  
            {  
                lastCharPosi = textBox1.Text.Length-1;  
            }  
    

    How do you define lastCharacterPosition?


    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