I have the following code:
private void txtNR_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
else
{
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
else
{
MessageBox.Show("You cannot type letters!");
}
}
My question is: when I am trying to type letters the warning message is coming up front but the same is happening when i'm trying to type numbers, and after i click ok on message, the number is writtend down inside. Can you help me understand why?
Your code should be like that:
if (!(char.IsControl(e.KeyChar) || char.IsDigit(e.KeyChar) || (e.KeyChar == '.')))
{
e.Handled = true;
MessageBox.Show("You cannot type letters!");
}
Replace
else { }
with
else
Because of extra {} the second if statement is executed even if first one is handled. Due to this you are seeing message box even if the character is digit (which is already handled)
Your condition is alright. You just need to set the Char to nothing
Try this:
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
else
{
MessageBox.Show("You cannot type letters!");
e.KeyChar = '\0';
}
I would suggest you to validate the content of the textbox after the user do his input ont it. Like #Sinatr said, for the user this could be an annoying thing to show a messagebox every time he writes wrong input.
It should also simplify your code, I think.
If the text is not numeric, then display the messagebox, something like that.
textbox_Validating(){
decimal d;
if(decimal.TryParse(textBox1.Text, out d))
{
//valid
}
else
{
//invalid
MessageBox.Show("Please enter a valid number");
return;
}
}
Something like that... Sorry for the eventual errors in the code.
Good luck.
You don't say what your overall aim is.
However to correctly handle the event you are after this will work. You don't really want a pop up message all the time, better validate on form submission.
Are you trying to make a decimal text box ?
You've also got to take into account copy and paste which these events just aren't going to cover.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
else
{ // only allow one decimal point
if ((e.KeyChar == '.'))
{
if (((TextBox) sender).Text.Contains("."))
{
e.Handled = true;
}
}
else
{
if (char.IsControl(e.KeyChar))
{
return;
}
if (!char.IsDigit(e.KeyChar))
{
MessageBox.Show("You cannot type letters!");
}
}
}
Related
I Tried Some Codes But Didnt Work
For Example
I Found This And It Didnt Work:
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;
}
You have a very simple, yet understandable error there.
The Handled property of KeyPressEventArgs should be set to true to keep the operating system from further processing the key.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keypresseventargs?view=netframework-4.8
In other words, set this to true when you want to PREVENT the key.
Therefore, change your code like this to ALLOW further processing when the pressed key fits the conditions.
Please also see how the boolean variables are introduced to make the code readable.
The code below allows
A ( - ) character if it is the first char in the text box
A ( . ) character if it is not the first char and if there are no other dots
Any control characters
And any digits.
Good luck.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
bool isControl = char.IsControl(e.KeyChar);
bool isDigit = char.IsDigit(e.KeyChar);
bool isDot = e.KeyChar == '.';
bool alreadyHasADot = (sender as TextBox).Text.IndexOf('.') != -1;
bool isHyphen = e.KeyChar == '-';
bool isFirstChar = (sender as TextBox).Text.Length == 0;
bool isAllowed =
isControl ||
isDigit ||
(isDot && !isFirstChar && !alreadyHasADot) ||
(isHyphen && isFirstChar);
if (!isAllowed)
{
e.Handled = true;
}
}
Sorry if this is a really basic question but I'm new to C# and it's my first windows form app.
In the code below my TextBox only accepts a decimal point ",", a minus sign "-", digits, and it also accepts the input of the delete and backspace keys (correct me if I'm wrong). So I can input and delete numbers like:
-12.31
-.31
The problem is I can also input something like:
12-
Is there a way to only input "-" if its the first character of the string? I tried google and I tried to come up with something but nothing seems to work.
And thank you for your time.
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && (e.KeyChar != ',') && (e.KeyChar != '-') && (e.KeyChar != (char)8))
{
e.Handled = true;
}
if ((e.KeyChar == ',') && ((sender as TextBox).Text.IndexOf(',') > -1))
{
e.Handled = true;
}
if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1))
{
e.Handled = true;
}
}
You can check where the cursor is by using SelectionStart:
var textBox = (TextBox)sender;
if (e.KeyChar == '-' && (textBox.SelectionStart !=0 || textBox.Text.Contains("-")))
{
e.Handled = true;
}
I need a textbox keypress handler which handles a decimal input range of 0 to 9999999999.99 value. I have this code below but is not serving the purpose. With it I cannot enter decimals after 10 digits.
public static void NumericWithDecimalTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
TextBox textBox = sender as TextBox;
string[] parts = textBox.Text.Split('.');
// only allow one decimal point
if (((e.KeyChar == '.') && (textBox.Text.IndexOf('.') > -1)) || (!char.IsControl(e.KeyChar) && ((parts[0].Length >= 10))))
{
e.Handled = true;
}
}
You could simplify the process by having the data validated, along the lines of:
public static void NumericWithDecimalTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
var textBox = sender as TextBox;
var enteredValue = textBox.Text;
var decimalValue = 0M;
if (decimal.TryParse(enteredValue, out decimalValue) && ValueIsWithinRange(decimalValue, 0M, 9999999999.99M))
{
Model.ThePropertyStoringTheValue = decimalValue; // wherever you need to store the value
}
else
{
// Inform the user they have entered invalid data (i.e. change the textbox background colour or show a message box)
}
}
private bool ValueIsWithinRange(decimal valueToValidate, decimal lower, decimal upper)
{
return valueToValidate >= lower && valueToValidate <= upper
}
That way, if the value is valid, it is written to the model (following good MVC design practices) and if it is invalid, the user is informed with a message that would allow them to make corrections (e.g. "the value you have entered isn't a valid decimal" or "the value must not be negative" etc.)
I have a voucher application, and when someone wants to create a campaign voucher, one of the fields they have to specify is "Target Audience". Sometimes the person might enter a string, or a variable that is not an int, and the server will just crash. I just want to implement an if statement to see if its NOT a int, and then do something. I have a regular expression, i just dont know how to implement it. Tried many things. (the textbox to validate is 'campaignAudience')
System.Text.RegularExpressions.Regex.IsMatch(campaignAudience.Value, "[ ^ 0-9]");
I have recently needed a similiar solution. Assuming you need an integer (number without decimal point).
public static bool IntegerAndIsANumber(this string val)
{
if (string.IsNullOrEmpty(val) || val.Contains(',') || val.Contains('.'))
return false;
decimal decimalValue;
if (!Decimal.TryParse(val, out decimalValue))
return false;
decimal fraction = decimalValue - (Int64)decimalValue;
if (fraction == 0)
return true;
return false;
}
It checks if given string is an Integer and if it is a number in the first place.
Using:
if(YourString.IntegerAndIsANumber()){
//value is Integer
}
else{
//incorrect value
}
P.S. Also have done Unit testing with this extension method.
Use a custom TextBox that only accepts numbers, add the following to your project, compile then the custom TextBox will appear at the top of the toolbox when your form is shown in the IDE. Add the TextBox to the form and now the user can only enter digits.
using System;
using System.Windows.Forms;
public class numericTextbox : TextBox
{
private const int WM_PASTE = 0x302;
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
string Value = this.Text;
Value = Value.Remove(this.SelectionStart, this.SelectionLength);
Value = Value.Insert(this.SelectionStart, e.KeyChar.ToString());
e.Handled = Convert.ToBoolean(Value.LastIndexOf("-") > 0) ||
!(char.IsControl(e.KeyChar) ||
char.IsDigit(e.KeyChar) ||
(e.KeyChar == '.' && !(this.Text.Contains(".")) ||
e.KeyChar == '.' && this.SelectedText.Contains(".")) ||
(e.KeyChar == '-' && this.SelectionStart == 0));
base.OnKeyPress(e);
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == WM_PASTE)
{
string Value = this.Text;
Value = Value.Remove(this.SelectionStart, this.SelectionLength);
Value = Value.Insert(this.SelectionStart, Clipboard.GetText());
decimal result = 0M;
if (!(decimal.TryParse(Value, out result)))
{
return;
}
}
base.WndProc(ref m);
}
}
Linq version:
if(campaignAudience.Value.All(x => Char.IsLetter(x)))
{
// text input is OK
}
Regex version:
if(new Regex("^[A-Za-z]*$").Match(campaignAudience.Value).Success)
{
// text input is OK
}
Limit the keypress event of the textbox to digits
So, I have a homework and I need help. I must restrict my textbox input to class number. Our classes are in format: "I-1", "II-1", "III-1", "IV-1", "I-10", "IV-10" and so on. So my code is:
private void tbRazred_KeyPress(object sender, KeyPressEventArgs e)
{ //ogranicenje textbox-a da moze da upisuje razred u formatu npr. IV-1
duzina = tbRazred.TextLength;
if (brprivremeni < duzina)
{
brprivremeni = duzina;
if (e.KeyChar.ToString() != "-")
switch (brslova)
{
case 1:
{
e.Handled = e.KeyChar != 'I'; brslova++;
break;
}
case 2:
{
e.Handled = e.KeyChar != 'I' && e.KeyChar != 'V'; brslova++;
break;
}
case 3:
{
if (tbRazred.Text == "IV") e.Handled = e.KeyChar != '-'; brslova++;
break;
}
case 4:
{
if (tbRazred.Text == "III") e.Handled = e.KeyChar != '-'; brslova++;
break;
}
}
else e.Handled = !char.IsDigit(e.KeyChar);
}
}
duzina gets the textbox length
btprivremeni is temporary value which gets the textbox length and its compared to the new textbox length, so if its same or lower it doesn't do anything. Please help me, I'm doing this for a couple days and now I must ask you.
There's a few different ways to do this. Since your list potential options is pretty small, I would put all of the "Class Numbers" into a list of strings. I would then check the textbox's text against that list with an Event Handler from some other control.
Textbox tbRazred = new Textbox();
List<string> classNumbers = new List<string>();
// Add all your items, here is one of them
classNumbers.Add("I-1");
// Call the following based on some checker routine or Control. Maybe when the Textbox loses focus?
bool pass = false;
foreach (string thisClass in classNumbers)
{
if (thisClass == tbRazred.Text)
{
pass = true;
}
}