C# inputs an ASCII character to the TextBox when I press Backspace - c#

I have used e.Handled bool of KeyPress event and let e.KeyChar only be D0-D9, ',' and Back. But then my program started inputting an ASCII character into the TextBox instead of erasing the most recent char when I pressed Backspace. Then I assigned;
if(e.KeyChar == (char)Keys.Back) {textBox1.Text = textBox1.Text + "\b"}
to erase the most recent char that was inputted. It still decided to input a weird ASCII character instead of erasing anything.

If you want to allow characters in '0'..'9' range only, while keeping all the other logic intact (for instance, if you select several characters and then press "BackSpace" only selection will be removed, not the last character) you can handle unwanted characters only:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
e.Handled = e.KeyChar >= ' ' && (e.KeyChar < '0' || e.KeyChar > '9');
}
Note, that e.KeyChar >= ' ' allowes all command characters (BS included)

this worked:
if (e.KeyChar == (char)Keys.Back)
{
textBox1.Text = textBox1.Text.Substring(0, (textBox1.Text.Length - 1));
}

Please try with the following code.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back &&
(e.KeyChar < (char)Keys.D0 || e.KeyChar > (char)Keys.D9))
{
e.Handled = true;
}
}

Related

KeyPress Event gives wrong value

I made a KeyPress Event and want to allow only Double values (or just digits and comma) so I tried this:
e.Handled = !(char.IsNumber(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Decimal);
But somehow he's got problems with the "Decimal". I'm using a german keyboard and when I try to enter the comma, he does nothing. When I press the "n" key he writes the letter. What is wrong here and how to solve that?
you can restrict the input using keyPress event like so:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c= e.KeyChar;
if (!char.IsDigit(c) && !char.IsControl(c))
{
e.Handled = true;
}
}
if we want to extend our restriction condition to accept a certain character (for example ,)
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c= e.KeyChar;
if (!char.IsDigit(c) && !char.IsControl(c) && c!=',')
{
e.Handled = true;
}
}
To avoid having multiple comma like 222,34545,454 we can do this work around:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c= e.KeyChar;
bool comma= textBox1.Text.Contains(','); //true in case comma already inserted
// accepts only digits, controls and comma
if (!char.IsDigit(c) && !char.IsControl(c) && c!=',')
{
e.Handled = true;
return;
}
// whenever a comma is inserted we check if we already have one
if (c == ',' && comma)
{
e.Handled = true;
}
}

Set Text to all caps when typing

Just want to ask how to set text to all caps when typing in textbox
I've tried this, but it's not working.
void txt_AllCaps(object sender, KeyPressEventArgs e)
{
string s = (sender as TextBox).Text.ToString().ToUpper();
(sender as TextBox).Text = s;
}
try:
YourTextBox.CharacterCasing = CharacterCasing.Upper;
You can change the e.KeyChar in the KeyPress event handler to what you want. Try this:
private void txt_AllCaps(object sender, KeyPressEventArgs e){
e.KeyChar = e.KeyChar.ToString().ToUpper()[0];
//Or this
//if (e.KeyChar > 96 && e.KeyChar < 123) e.KeyChar = (char) (e.KeyChar - 32);
}
You should choose the solution of Shree, it's much more convenient :)

how enter in TextBox only digits from interval

I try to make some form (C#, WinForms) for small program Reminder.
During it i have some problem - whant to make some filter for textBox where user must enter start time for event.
As result got next - on KeyPress event add some code, the allow enter only digits, but also i want that user can enter only digits from some diapasone.
code:
private void starTimetextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= '0') && (e.KeyChar <= '9'))
{
return;
}
if (Char.IsControl(e.KeyChar))
{
if (e.KeyChar == (char) (Keys.Enter))
startTimeMMtextBox.Focus();
}
e.Handled = true;
}
can i do this by using this event or no?
Try this:-
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
NOTE:- You can use TextBox's MaxLength property to restrict user to enter only 2 digits. To display message to user you can use TextChanged event of TextBox.
To make a filter on the characters 0 to 9, you can extend the previous answer.
(Similair as in your question sample).
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)
&& (e.KeyChar >= '0' && e.KeyChar <= '9');
}

can't determine '.' keychar for a textbox KeyPress event

I use below code to not allowing any character except numbers in a textbox ... but it allows '.' character! I don't want it to allow dot.
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
e.KeyChar != (char)(Keys.Delete) &&
e.KeyChar != (char)(Keys.Back)&&
e.KeyChar !=(char)(Keys.OemPeriod))
{
e.Handled = true;
}
}
use this:
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back)
)
it is because Keys.Delete's char value is 46 which is the same as '.'. I do not know why it likes this.
You could try this instead (where textBox1 would be your textbox):
// Hook up the text changed event.
textBox1.TextChanged += textBox1_TextChanged;
...
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Replace all non-digit char's with empty string.
textBox1.Text = Regex.Replace(textBox1.Text, #"[^\d]", "");
}
Or
// Save the regular expression object globally (so it won't be created every time the text is changed).
Regex reg = new Regex(#"[^\d]");
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (reg.IsMatch(textBox1.Text))
textBox1.Text = reg.Replace(textBox1.Text, ""); // Replace only if it matches.
}
//This is the shortest way
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
try this code for your problem in keypress event :
private void txtMazaneh_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && (int)e.KeyChar != 8 ||(e.KeyChar= .))
e.Handled = true;
}

Textbox with decimal input improvement

I have a textbox that gets a decimal value say 10500.00 the problem is that the way I have it, when you enter a value and then enter the decimals it would not allow you to backspace or clear the textbox to input a new value.. it just gets stuck.. I have tried to set the value back to 0.00 but i think i placed it on the wrong place because it wont change it. Here is my code
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), #"\.\d\d");
if (matchString)
{
e.Handled = true;
}
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;
}
}
What type of change do you suggest so that I may be able to backspace or clear the texbox an enter a new value?.
You can trap for the Backspace (BS) char (8) and, if found, set your handle to false.
Your code may look like this...
....
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (e.KeyChar == (char)8)
e.Handled = false;
A suggestion to make your code a bit more intuitive to interpret what your event handler is doing, you may want to create a var that implies the logic you are implementing. Something like...
private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
bool ignoreKeyPress = false;
bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), #"\.\d\d");
if (e.KeyChar == '\b') // Always allow a Backspace
ignoreKeyPress = false;
else if (matchString)
ignoreKeyPress = true;
else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
ignoreKeyPress = true;
else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
ignoreKeyPress = true;
e.Handled = ignoreKeyPress;
}
Easiest way would be :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '\b')
{
e.Handled = true;
}

Categories