I want to do something like a calculator erase button or to be more specific I want to delete the last character when a textbox is changed and not a number is written. Like in Java I guess you could use CharAt() method but how about C#?
4 Answers
For the text box, just handle the KeyPress event, like this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
}
4 Comments
DonBoitnott
This is the only real answer so far...the question is poorly titled and worded. It's really about ensuring only digits get entered.
tnw
@DonBoitnott Even more confusing, OP seems satisfied with Daniel's response anyway.
Daniel Abou Chleih
@DonBoitnott How do you know that this is the real answer? Maybe he already got that and did not know how to delete a char. The question was clear to me: How to delete last Char in String. Anyway +1 for Karl's answer because it will complete this whole mess
DonBoitnott
@tnw I agree, it is, but the wording is there nonetheless. Perhaps Daniel is right, I dunno. Just seemed like too many people jumped before reading.
Try substring:
var myTextBox = GetMyTexBoxFromSomewhere();
myTextBox.Text = myTextBox.Text.Substring(0, myTextBox.Text.Length - 1);
In the spirit of doing it "right"... if you're using windows forms:
private void tbCalculatorLikeInput_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
And if you're using ASP.NET WebForms:
<asp:TextBox id="txtNumbersOnly" Runat="server" />
<asp:RegularExpressionValidator Runat="server" ID="valNumbersOnly" ControlToValidate="txtNumbersOnly" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box." ValidationExpression="(^([0-9]*|\d*\d{1}?\d*)$)">
</asp:RegularExpressionValidator>
And if you're using HTML5 / MVC:
<input type="number" />
Comments
Use following code:
stringName = stringName.Remove(stringName.Length - 1);
MSDN: http://msdn.microsoft.com/en-us/library/system.string.remove.aspx
Put the code into the TextBox.TextChanged Event-Method
remove last character in string c#and find not 1, not 2, not even 3, but 4 duplicates of this exact question on StackOverflow alone