How to disallow the input of some punctuations - c#

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

Related

Textbox without special chars

I want my textbox to never accept special chars.
Only accepts space,numbers and letters.
I found this code for Presskey event:
private void rsNameTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
}
But it doesnt work when someone paste something in the textbox. How can I make a textChanged event equivalent?
I tried replacing the not accepted chars for "" with this function but its not working.Its showing any chars when I paste and for some reason its erasing the default initial text "text1":
private void rsNameTextBox_TextChanged(object sender, EventArgs e)
{
Regex reg = new Regex(#"^[\s\dA-Za-z]+$");
rsNameTextBox.Text = reg.Replace(rsNameTextBox.Text,"");
}
why you are not using ShortcutsEnabled propety of the TextBox you
want to prevent cut,copy and paste features.
and then you can use your code in rsNameTextBox_KeyPress
Here is the link ,How to prevent paste features in Window Form Application.

c# apply same rules to all textboxes

I have several text boxes and would like to format them all the same way with these rules:
// limits to number, control keys, and decimal
// goes to the next text box when enter
private void tb_text1_KeyPress_1(object sender, KeyPressEventArgs e)
{
string newString = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
tb_text1.MaxLength = 6;
e.Handled = (!char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.');
if (e.KeyChar == (char)(Keys.Enter))
{
this.GetNextControl(ActiveControl, true).Focus();
}
}
// removes restricted chars
private void tb_text1_Enter(object sender, EventArgs e)
{
tb_text1.Text = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
}
// applies format at exit
private void tb_text1_Leave(object sender, EventArgs e)
{
tb_text1.Text = string.Format("{0,-6} [Ohm]", decimal.Parse(tb_text1.Text));
}
What is the best way? create a new text box class based on the text box?
Thanks.
Replace in methods your "tb_text1" variable to the "((TextBox)sender)", and now You can use Your code for any textbox.
It is very easy to do it with javascript . Please try that. I have done it i'm not able to find piece of that code right now . It is worth the effort because it will be very fast and will be running on client side.

Restrict Characters Allowed In TextBox(Entering Money Amount)

So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.
Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion).
Then you can use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
{
e.Handled = !char.IsNumber(e.KeyChar);
}
}
All validation should be performed manually on KeyPress event.
Here described validation for numeric values values. You will need to check the '$' sign and decimals additionally.
I think you are using WinForms and not WPF. If that is the case then you could use System.Windows.Forms.ErrorProvider (you can drag-drop one from toolbox to your form) along with regular expressions to do the validation.
WARNING: The regex pattern string below may not do exactly you want but hopefully conveys the idea.
Some match examples... "$4,000.00", "-$4000.00", "-$400.00"
private void textBox1_Validating(object sender, CancelEventArgs e)
{
string error = null;
string pattern = #"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$";
if (!Regex.IsMatch(textBox1.Text, pattern))
{
error = "Please enter a US currency value.";
e.Cancel = true;
}
errorProvider1.SetError((Control)sender, error);
}
There are a number of articles on numeric textboxes
Numeric TextBox
http://www.daniweb.com/software-development/csharp/threads/95153
http://www.codeproject.com/KB/vb/NumericTextBox.aspx
I use this one in my projects
http://www.codeproject.com/KB/edit/ValidatingTextBoxControls.aspx
//tb - is the name of text box
private void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
char[] inputChar = e.Text.ToCharArray();
if (char.IsNumber(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
// another method.
if (char.IsDigit(inputChar[0]))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
Have you tried Ajax Controls?
http://www.aspsnippets.com/Articles/ASPNet-AJAX-FilteredTextBoxExtender-Control-Example.aspx
Simples. :)

Having a MaskedTextBox only accept letters

Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Mask = "*[L]";
maskedTextBox1.MaskInputRejected += new MaskInputRejectedEventHandler(maskedTextBox1_MaskInputRejected);
}
How can I set it to accept only letters, but however many the user wants? Thanks!
This would be easy if masked text boxes accepted regular expression, but unfortunately they don't.
One (albeit not very pretty) way you could do it is to use the optional letter ? mask and put in the same amount as the maximum length you'll allow in the text box, i.e
maskedTextBox1.Mask = "????????????????????????????????.......";
Alternatively you could use your own validation instead of a mask and use a regular expression like so
void textbox1_Validating(object sender, CancelEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textbox1.Text, #"^[a-zA-Z]+$"))
{
MessageBox.Show("Please enter letters only");
}
}
Or yet another way would be to ignore any key presses other than those from letters by handling the KeyPress event, which in my opinion would be the best way to go.
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"^[a-zA-Z]+$"))
e.Handled = true;
}
If you want only letters to be entered you can use this in keyPress event
if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar)) //The latter is for enabling control keys like CTRL and backspace
{
e.Handled = true;
}

c# Numeric Text box

I want to create separate textbox for numbers and string using c# code. I should not use jquery or javascript. Can anyone pls help me.
Condition:
Numeric Textbox: It should not allow characters, special characters.
String Textbox: Should not allow numbers, Special characters.
I think you can use Masked C# TextBox Control
Have a look at the Validation Controls ; these include client-side (javascript) and server-side validation logic.
for numbers only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int isNumber = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}
for text only
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
int Length=textbox1.Length;
int Loop;
for(Loop=1;Loop<=Length;Loop++)
{
char c=textbox1.subString(Loop,1);
if(( c<'a' && c>'z') || (c<'A' && c>'Z'))
{
Messagebox.Show("Please Enter Only Alphabets");
e.Handle=true;
}
}
}

Categories

Resources