Textbox without special chars - c#

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.

Related

How can I make a TextBox accepts only numeric values in WinUI 3?

I have a TextBox which I use in Settings page of my app. Now, this textbox should only accept/display digits. There are several examples and solutions for this problem however, none of them work for WinUI 3 as they are mostly from 5-10 years ago.
KeyPress event does not exists in WinUI 3 TextBox. While looking for alternatives I saw KeyDown event however this event arguments are different and KeyRoutedEventArgs do not contain any property like KeyChar.
The example code I found that's applicable for WPF applications:
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
How can I achieve this behaviour in WinUI 3 TextBox?
You can use InputScope!
You can find a reference from the Microsoft docs.
Here's an example from Microsoft:
<TextBox Header="Telephone Number" InputScope="TelephoneNumber"/>
You can also do further verifications in the code-behind by listening to the TextChanged event:
<TextBox TextChanged="OnTextChanged" />
<!-- In your code-behind file -->
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
// Get the current text of the TextBox
var text = ((TextBox)sender).Text;
// Use a regular expression to only allow numeric values
var regex = new Regex("^[0-9]*$");
// If the text does not match the regular expression, undo the change
if (!regex.IsMatch(text))
{
((TextBox)sender).Undo();
}
}
Edit:
In WinUI 3, you can use KeyDown event too.
It's very similar to the way you did in WPF:
<TextBox KeyDown="OnKeyDown" />
private void OnKeyDown(object sender, KeyRoutedEventArgs e)
{
// Check if the key pressed is a numeric key
if (!((e.Key >= VirtualKey.Number0 && e.Key <= VirtualKey.Number9) || (e.Key >= VirtualKey.NumberPad0 && e.Key <= VirtualKey.NumberPad9)))
{
// If the key is not numeric, cancel the event and prevent the key from being entered
e.Handled = true;
}
}
#Link Hylia's answer was somehow correct in achieving the behaviour requested. I expanded on that answered by:
Changed the event used. The KeyDown or TextChanged events were asynchronous events and would not block the entered input to appear on the screen. I changed this to TextChanging event which is run synchronously and before the TextBox.Text is rendered. Using this method, I can control the text before its rendered and improve UX.
Instead of undoing, I now do just remove the char entered from the text and pass it back to the TextBox.
I put the cursor back to where it was before so that the user can continue typing from where they left.
The code can be found below:
private void textBox1_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
var currentPosition = textBox1.SelectionStart - 1;
var text = ((TextBox)sender).Text;
var regex = new Regex("^[0-9]*$");
if(!regex.IsMatch(text))
{
var foundChar = Regex.Match(textBox1.Text, #"[^0-9]");
if(foundChar.Success)
{
textBox1.Text = textBox1.Text.Remove(foundChar.Index, 1);
}
textBox1.Select(currentPosition, 0);
}
}

C# maskedTextbox, how to disable whitespaces?

I cant figure out how to disable whitespaces, I tried multiple things, and yes my mask is 00000000000 but still it allows whitespaces. Anyone know a fix?
Not much code to show, only:
Should only allow numbers to be entered, not whitespaces too :/
Add the KeyDown Event to your textbox and then add the following Code in the created method:
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
e.Handled = true;
e.SuppressKeyPress = true;
return;
}
}

Default editing commands not working in TextBox when filtering KeyPress

I have a textbox in my winform in which after puting a validation using regex on keypress event, the default functionalities like copy paste etc of the textbox is not working.
How can i handle this?
Regex used code
private void textbox_keypress(object sender,keypresseventargs e)
{
var regex= new regex(#"^[0-9,]*$");
if(!regex.ismatch(e.keychar.tostring()))
{
e.handled=true;
}
}
after removing the keypress event handler everything is working fine but i have to restrict user to enter comma separated number value and also copy paste delete backspace in that textbox.
The Ctrl-Commands don't work because you abort their entries. To avoid this you must either
check if the Ctrl-Key has been pressed. The KeyPress event doesn't tell you that. This example from MSDN shows you how to do it: You script the KeyDown event to set (or clear) a flag variable, which you can then test in the KeyPress. No, not exactly elegant imho, but that's how MS tells you to do it.. (Note that I have added the Backspace code \b, as it isn't covered by the Ctrl-check..)
bool ctrlPressed = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
ctrlPressed = (Control.ModifierKeys == Keys.Control);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!ctrlPressed)
{
var regex= new Regex(#"^[0-9,\b]*$");
if (!regex.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
}
Or, if you want better control over which Ctrl-Keys are allowed, skip the whole flags-affair and instead simply include them one by one in the allowed keys-brackets like this for ^C, ^X, ^A, ^V ^Z etc..:
var regex= new Regex(#"^[0-9,\b\cC\cX\cA\cV\cZ]*$");
Here is the description from MSDN:
\cX Matches an ASCII control character, where X is the letter of the
control character. For example, \cC is CTRL-C.
On a side note: The old fashioned copy&paste commands of Ctl-Ins and Shift-Ins work as normal even in your original code.

Using backspace to move back to previous textBox (C#)

This may be a simple question. I'm new to C# (and most programming) and I am trying to make a program that consists of two text boxes. The information in these textboxes will frequently be deleted and new information will need entered, so it needs to be quick. For convenience I'm trying to make the backspace key refocus on the previous textbox rather than using Shift+Space or clicking. Here is what I have. The program runs, but the code below doesn't seem to do what I intend it to do.
if (e.KeyCode == Keys.Back && textBox2.TextLength == 0)
textBox1.Focus();
So, when textbox2 has 0 characters and backspace is subsequently keyed, I would like it to move back to textbox1. Thanks for any help.
So to make this work you're going to need to make sure you run this code on KeyUp, but you also do not need multiple KeyUp handlers to do this. Consider this KeyUp handler:
private void textBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null) { return; }
if (e.KeyCode == Keys.Back && textBox.Text.Length == 0)
{
// this here of course being the Form
// Select causes the form to select the previous control in the tab order
this.Select(true, false);
}
}
Now just attach this handler to all text boxes that you want to behave this way and they'll all work.
I did get it to work finally. What I did wasn't too different than what I was trying before, but here is how I did it.
I created two text boxes from the .cs [Design] view.
I selected each box and clicked the "Events" lightning bolt icon under Properties. This is something I left out previously when this didn't work.
I set both of them to KeyPress and TextChanged (i.e. textBox1_KeyPress & textBox1_TextChanged (Did the same thing with textBox2). I don't know if this is part of the reason why it worked. I'm just documenting my actions.
I double clicked each textBox, which created an EventArgs for each. This is where I stored my regular code.
In addition to the EventArgs I manually created a KeyEventArgs (see below) where I put the function for the Backspace. Here is the code:
// Here is the KeyEventArgs I created using KeyPress (Public).
public void textBox2_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back && textBox2.Text.Length == 0)
textBox1.Focus();
}
// Here is where the rest of my code (Private).
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "A")
richTextBox3.Text = "January";
if (textBox2.Text == "B")
richTextBox3.Text = "February";
if (textBox2.Text == "C")
richTextBox3.Text = "March";
// Code Continues...
Sorry if this isn't clear. I just wanted to document what I did in case it helps someone later. Thanks for the help everyone.

Allow only valid characters in a Windows file system in a TextBox that can only appear as uppercase in Windows Forms?

How can only valid characters be allowed in a Windows file system in a TextBox that can only appear as uppercase in Windows Forms?
Is there an easy way for this?
About the set of characters allowed in a Windows file system (Char.IsLetterOrDigit is not enough)
How do I make the typed characters uppercase?
Create a Textbox key press handler and Use Path.GetInvalidPathChars(), Path.GetInvalidFileNameChars() to check for a valid char and return the uppercase version if the char is valid.
textBox1.CharacterCasing = CharacterCasing.Upper;
...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Path.GetInvalidFileNameChars().Contains(e.KeyChar) ||
Path.GetInvalidPathChars().Contains(e.KeyChar))
{
e.Handled = true;
}
}
[Of course, it would be more reusable to create a method rather than placing this code directly in the handler.]
UPDATED to reflect comments.
Here's my solution. It works perfectly for windows file names convention. Cheers.
// Prevent user from wrong input - \/:*?"<>|
private void textBoxMP3Name_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), #"[^?:\\/:*?\""<>|]"))
{
e.Handled = true;
}
}
A Better way for me was to use the TextChanged Event ala:
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
...
private void textBox1_TextChanged(object sender, EventArgs e)
{
char[] invalidChars = Path.GetInvalidFileNameChars();
textBox1.Text = string.Join("", textBox1.Text.Split(invalidChars));
textBox1.SelectionStart = textBox1.Text.Length + 1;
}
because ... you need backspace and user simply love copy & paste ...

Categories

Resources