I have a Winform with some edit boxes.
The form can be loaded in other languages too, like chinese!
the requirement is that certain textboxes should accept only English chars
for Example When user types in Tex box 1, it should be in english
Whereas in if he types in Text box 2 and 3 it should be in Chinese ?
Is it possible to do something like this !
Yes, it's certainly possible. You can add a validation event handler that checks the character. You could have a dictionary of permissible characters, or if you restrict the character to a certain encoding (perhaps UTF-8), you could compare the character to a range of characters using < and >.
To be more specific: You can handle the KeyPress event. If e.KeyChar is invalid, set e.Handled to true.
Try this:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (System.Text.Encoding.UTF8.GetByteCount(new char[] { e.KeyChar }) > 1)
{
e.Handled = true;
}
}
For handle copy and paste, try the following. It may not be the best solution, but it will trim away non-UTF8 char.
private void Control_KeyDown(object sender, KeyEventArgs e)
{
//Prevent the user from copying text that contains non UTF-8 Characters
if (!e.Control || e.KeyCode != Keys.V)
return;
if (Clipboard.ContainsText() &&
Clipboard.GetText().Any(c => System.Text.Encoding.UTF8.GetByteCount(new[] {c}) > 1))
{
char[] nonUtf8Characters =
Clipboard.GetText().Where(c => System.Text.Encoding.UTF8.GetByteCount(new[] {c}) <= 1).ToArray();
if (nonUtf8Characters.Length > 0)
{
Clipboard.SetText(new String(nonUtf8Characters));
}
else
{
Clipboard.Clear();
}
e.Handled = true;
}
}
Related
I have a textbox that accepts only numbers, no other characters. And I created the following function in the keypress method for that:
private void txtRGIE_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != (char)8)
{
e.Handled = true;
}
}
Validation is working when I type, I can't type special characters or letters like I wanted. However, if I copy a numeric string that contains dots or other characters and paste it into the field, it accepts normally. For example, if you copy: 323.323 / 323 and paste into the field, it will accept. How do I validate the characters I paste, allowing only numbers?
I have a textbox that accepts only numbers
And that's the flaw; saying "I have a knife here that i'm trying to use as a screwdriver, but i keep cutting myself with it, so i filed it smooth, but it's too big to get into the screw hole, so I filed it small, but it doesn't turn a + shaped screw very well, and the tip isn't hardened so it keeps breaking.."
The answer is to use a + shaped screwdriver, rather than keep repeatedly trying to kludge something not made for the job, into something that will do the job
A NumericUpDown control is the right tool for this job; it accepts only numbers, has configurable decimal places, and upper and lower limits, cannot have alphameric text typed or pasted into it and, bonus, the user can use the Up and Down cursor keys to change the value
NUD is a drop in replacement for your textbox, it's free and it's part of the standard lib so there isn't anything to install - just remember to get the .Value, not the .Text, and that it's a decimal, so you might want to cast it to something else to use it (double? int?) depending on what your app expects
If you don't like the little up down buttons, see here
you can use :
private void txtRGIE_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;
}
}
or you can use a NumericUpDown instead
refer to this answers so you understand more.
You could use a MaskedTextBox instead of a regular one.
As already mentioned a NumericUpDown control is a good choice and to make it appear like a TextBox you can hide the up/down arrows e.g.
amountNumericUpDown1.Controls[0].Hide();
Or create a custom version with no up/down arrows and in this case no beep when pressing enter key.
public class SpecialNumericUpDown : NumericUpDown
{
public SpecialNumericUpDown()
{
Controls[0].Hide();
TextAlign = HorizontalAlignment.Right;
}
protected override void OnTextBoxResize(object source, EventArgs e)
{
Controls[1].Width = Width - 4;
}
public delegate void TriggerDelegate();
public event TriggerDelegate TriggerEvent;
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == (Keys.Return))
{
e.Handled = true;
e.SuppressKeyPress = true;
TriggerEvent?.Invoke();
return;
}
base.OnKeyDown(e);
}
}
I have a textbox, in Windows Form, for the input from a user. I want him to allow some punctuations but disallow others. How can I fix that? I have the next code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) &&
!char.IsLetter(e.KeyChar) &&
!char.IsPunctuation(e.KeyChar) &&
!char.IsWhiteSpace(e.KeyChar))
{
e.Handled = true;
}
}
One way to approach this is to look at the string they inputted as an array of chars:
char[] strarray = userinput.ToCharArray();
And then just create an if statement to look for the punctuation for example:
if(strarray.Contains(' the punctuation you don't want')){
// provide user input to tell the user to input a new string and reset the text box
}
Hope that Helps
I have a textbox in my application which I only want the user to be able to choose the "minus", "comma", "digits" and "back" from the keyboard. Can only make the user use digits and the back key, the rest doesn't work.
private void BoxMaxY_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back ||
!(e.KeyChar == (char)Keys.OemMinus || !(e.KeyChar == (char)Keys.Oemcomma))))
{
e.Handled = true;
}
}
Because your code says: handle if it's not minus or not comma, remove the "!" from those checks.
Im using VS2010, and I have a text box... I assign a KeyPress on the box, abd set the method like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
I noticed that i am no longer able to enter any special keys such as the minus (-) and plus (+) sign into the textbox. Can someone please explain to me why i am no longer able to do this, and what i can do to fix this?
Ultimately I'm trying to only allow numeric keys to be entered, and i also want to allow the (-) minus sign, but if i cant get the minus sign in there, then i guess i wont be able to limit the text of the box
This should finish the job for you.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
e.Handled = true;
}
Here is how it works. If the character typed is one that you want, simply return from the function and let the normal handler take care of it. All other characters are marked as handled and so processing on them stops. Since nothing is done with them they are essentially thrown away. You could put everything in one if statement but I left it this way for clarity
I changed your code a little and added logic that only accepts 1, 2 or +, which was one of your problem characters. Hope this helps you!
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+') textBox1.AppendText(e.KeyChar.ToString());
}
Actually, you should do like so:
private void MyButton_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1' || e.KeyChar == '2' || e.KeyChar == '+')
e.Handled = false;
else
e.Handled = true;
}
Of course, you'll want to replace the individual tests by a method that will return whether or not the key is allowed.
Cheers
As it is now, your code won't allow anything to be entered. The e.Handled statement cancels the key stroke. The code below will allow any numeric character, and the minus sign. If you only want the minus sign in the first position in the textbox you will have to test the TextLength property before allowing the character.
private void MyButton_KeyPress(object sender, KeyPressEventArgs e
{
int i = 0;
if (!int.TryParse(e.KeyChar.ToString(), out i))
{
if (e.KeyChar.CompareTo('-')!=0)
{
e.Handled = true;
}
}
}
How can I put mask on win form text box so that it allows only numbers?
And how it works for another masks data, phone zip etc.
I am using Visual Studio 2008 C#
Thanks.
You can use the MaskedTextBox control
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Do you want to prevent input that isn't allowed or validate the input before it is possible to proceed?
The former could confuse users when they press keys but nothing happens. It is usually better to show their keypresses but display a warning that the input is currently invalid. It's probably also quite complicated to set up for masking an email-address regular expression for example.
Look at ErrorProvider to allow the user to type what they want but show warnings as they type.
For your first suggestion of a text box that only allows numbers, you might also want to consider a NumericUpDown.
Control the user's key press event to mask the input by not allowing any unwanted characters.
To allow only numbers with decimals:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
To allow only phone numbers values:
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
if (e.KeyChar == 8) return;
e.Handled = true;
}
As said above, use a MaskedTextBox.
It's also worth using an ErrorProvider.
Use Mask Text box and assign MasktextboxId.Mask.
If u want to use textbox then you have to write Regular Expression for it