Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the last character from a TextBox?

Tags:

c#

I'm trying to write a copy of MS Windows Calculator - just to exercise the knowledge I have acquired in the course I'm doing - and I'm having problems to write the Backspace key, but I have no idea about how to delete the last character on TxtResult.Text (Text Box). So, can some one teach me how to do that?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ZigndSuperCalc
{
    public partial class FrmZigndSC : Form
    {
        Int64 aux, result;
        Int16 cont = 0;
        bool sucess;
        public FrmZigndSC()
        {
            InitializeComponent();
        }

        private void BtnSoma_Click(object sender, EventArgs e)
        {
            sucess = Int64.TryParse(TxtInput.Text, out aux);
            result += aux;
            TxtInput.Text = Convert.ToString(result);
            TxtInput.Focus();
        }

        private void BtnCE_Click(object sender, EventArgs e)
        {
            TxtInput.Text = "0";
        }

        private void BtnC_Click(object sender, EventArgs e)
        {
            result = 0;
            TxtInput.Text = "0";
        }

        private void BtnBackspace_Click(object sender, EventArgs e)
        {
            // write here a method to delete the last character from 
        }
    }
}
like image 448
Zignd Avatar asked Nov 18 '25 01:11

Zignd


1 Answers

If we're mimicking calc.exe, exactly then it's probably something like:

string s = TxtResult.Text;

if (s.Length > 1) {
    s = s.Substring(0, s.Length - 1);
} else {
    s = "0";
}

TxtResult.Text = s;

EDIT: As requested, the Substring method I'm using here extracts a portion of the string and assigns it to the Text property of the textbox. See: http://msdn.microsoft.com/en-us/library/aka44szs.aspx

like image 74
rein Avatar answered Nov 20 '25 16:11

rein