Uppercase data enter at application level - c#

One of our clients wants all entered data to be uppercased. I don't want to do it textbox by textbox, etc.
Are the any way to do it at application level?

Solution 1: if you want to read UserInput in UpperCase you can use ToUpper() method.
Try This:
String str=textBox1.Text.ToUpper();
Solution 2:
if you want to Displayand read the UserInput in UpperCase, you can handle the TextChanged event of the TextBox as below:
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.ToUpper();
textBox1.Select(textBox1.Text.Length, 0);
}

You can write the KeyPress event once.
private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
e.KeyChar -= (char)32;
}
32 is just the difference in ASCII values between lowercase and uppercase letters.

You can subclass the TextBox control, create a derived class that only works with uppercase, and use your derived class instead of the original TextBox.
This is a possible way to implement it:
using System;
namespace UpperCaseTextBox
{
public class UpperCaseTextBox : System.Windows.Forms.TextBox
{
protected override void OnTextChanged(EventArgs e)
{
var selectionStart = this.SelectionStart;
var selectionLength = this.SelectionLength;
this.Text = this.Text.ToUpper();
this.SelectionStart = selectionStart;
this.SelectionLength = selectionLength;
base.OnTextChanged(e);
}
}
}
The above code has been tested, although it is just for demostration.
Note 1: I recommend to do this in a separated dll project, it will be easier to use (you have to compile build the control before placing it in the forms designer) and maintain. If you decide to create the dll, remember that you need to add a reference in the dll to System.Windows.Forms and also that you need a reference to your dll in your winforms application to use it.
Note 2: You may be interested in creating a variant of this by adding a new property to set the TextBox to normal, uppercase only or lowercase only. You may also want to create a mechanism to control this property for all the instances in your AppDomain (hint: that can be a static field). Why? Because you don't know what else will the client ask for next.

Related

Format textbox with numbers only

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);
}
}

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.

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.

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 ...

Allow only alphanumeric in textbox

I have a textbox that should disallow entering any special characters.
The user can enter :
A-Z
a-z
0-9
Space
How can I make the KeyDown event to do this?
Handling the KeyDown or KeyPress events is one way to do this, but programmers usually forget that a user can still copy-and-paste invalid text into the textbox.
A somewhat better way is to handle the TextChanged event, and strip out any offending characters there. This is a bit more complicated, as you have to keep track of the caret position and re-set it to the appropriate spot after changing the box's Text property.
Depending on your application's needs, I would just let the user type in whatever they want, and then flag the textbox (turn the text red or something) when the user tries to submit.
Just wanted to add some code for those ending up here by search:
private void Filter_TextChanged(object sender, EventArgs e)
{
var textboxSender = (TextBox)sender;
var cursorPosition = textboxSender.SelectionStart;
textboxSender.Text = Regex.Replace(textboxSender.Text, "[^0-9a-zA-Z ]", "");
textboxSender.SelectionStart = cursorPosition;
}
This is a change filter, so handles copy and paste, and preserves cursor position so that changing text in the middle works properly.
Note it uses the 'sender' to get the control name, allowing this one function to be linked to multiple textbox boxes, assuming they need the same filter. You can link multiple controls by going to the event section of a control and manually picking the function for the TextChanged event.
Use a regex to filter out the other characters. Or use Char.IsDigit, IsXXX methods to filter out unwanted characters. Lots of ways to do this.
Update: If you must use KeyDown then it seems that you need to also handle KeyPressed and set obEventArgs.Handled = true to disallow the characters. See the example on the KeyDown MSDN Page
Update: Now that you specify it's WPF. The below code will allow only a-z and A-Z characters to be entered into the textbox. Extend as needed...
private void _txtPath_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key < Key.A) || (e.Key > Key.Z))
e.Handled = true;
}
This will break if you copy-paste stuff into the text-box. Validate the entire text once the user leaves the control or when he clicks OK/Submit as MusicGenesis says.
private void _txtPath_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Key < Key.A) || (e.Key > Key.Z))
e.Handled = true;
}
I think it's worth considering doing the filtering on the TextBox's TextChanged event. You can create an operation that gets rid of any non-valid characters from your text string. This is a bit more messy than blocking the KeyDown event.
But, I think this is the way to go because you are not blocking WPF's built-in KeyDown/Up event handling mechanisms, so copy/paste still works. You would be working at a higher level of abstractions so I think it will be easier to figure out what is going on.
I ran into this in silverlight and wrote something like this.
private string _filterRegexPattern = "[^a-zA-Z0-9]"; // This would be "[^a-z0-9 ]" for this question.
private int _stringMaxLength = 24;
private void _inputTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(_filterRegexPattern))
{
var text = _inputTextBox.Text;
var newText = Regex.Replace(_inputTextBox.Text, _filterRegexPattern, "");
if (newText.Length > _stringMaxLength)
{
newText = newText.Substring(0, _stringMaxLength);
}
if (text.Length != newText.Length)
{
var selectionStart = _inputTextBox.SelectionStart - (text.Length - newText.Length);
_inputTextBox.Text = newText;
_inputTextBox.SelectionStart = selectionStart;
}
}
}
I accomplish this with a custom Dependency Property. It's reusable for any TextBox control, is much faster and more efficient to use than building key events, and makes my code files much cleaner.
In addition, it can handle other input methods which does not trigger key events, such as pasting a value into the TextBox using the mouse.
The code for the custom DP looks like this:
// When set to a Regex, the TextBox will only accept characters that match the RegEx
/// <summary>
/// Lets you enter a RegexPattern of what characters are allowed as input in a TextBox
/// </summary>
public static readonly DependencyProperty AllowedCharactersRegexProperty =
DependencyProperty.RegisterAttached("AllowedCharactersRegex",
typeof(string), typeof(TextBoxProperties),
new UIPropertyMetadata(null, AllowedCharactersRegexChanged));
// Get
public static string GetAllowedCharactersRegex(DependencyObject obj)
{
return (string)obj.GetValue(AllowedCharactersRegexProperty);
}
// Set
public static void SetAllowedCharactersRegex(DependencyObject obj, string value)
{
obj.SetValue(AllowedCharactersRegexProperty, value);
}
// Events
public static void AllowedCharactersRegexChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var tb = obj as TextBox;
if (tb != null)
{
if (e.NewValue != null)
{
tb.PreviewTextInput += Textbox_PreviewTextChanged;
DataObject.AddPastingHandler(tb, TextBox_OnPaste);
}
else
{
tb.PreviewTextInput -= Textbox_PreviewTextChanged;
DataObject.RemovePastingHandler(tb, TextBox_OnPaste);
}
}
}
public static void TextBox_OnPaste(object sender, DataObjectPastingEventArgs e)
{
var tb = sender as TextBox;
bool isText = e.SourceDataObject.GetDataPresent(DataFormats.Text, true);
if (!isText) return;
var newText = e.SourceDataObject.GetData(DataFormats.Text) as string;
string re = GetAllowedCharactersRegex(tb);
re = string.Format("[^{0}]", re);
if (Regex.IsMatch(newText.Trim(), re, RegexOptions.IgnoreCase))
{
e.CancelCommand();
}
}
public static void Textbox_PreviewTextChanged(object sender, TextCompositionEventArgs e)
{
var tb = sender as TextBox;
if (tb != null)
{
string re = GetAllowedCharactersRegex(tb);
re = string.Format("[^{0}]", re);
if (Regex.IsMatch(e.Text, re, RegexOptions.IgnoreCase))
{
e.Handled = true;
}
}
}
And it's used like this:
<TextBox Text="{Binding SomeValue, UpdateSourceTrigger=PropertyChanged}"
local:TextBoxHelpers.AllowedCharactersRegex="a-zA-Z0-9\s" />
I know that winForms have available a MaskedTextBox control, which lets you specify exactly this sort of thing. I don't know WPF, so I dunno if that's available there, but if it is, do that. Its MUCH easier than all this stuff with keypresses and events, and more robust too.
The easiest way to do this would be to included the Extended WPF Toolkit which has a control for doing exactly what you are asking for by specifying a mask.
http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox&referringTitle=Home
It will also display the mask in the text box as you are inputting if required.
(It also has many other useful controls)
and your regExp could look like [0-9a-zA-Z]* to allow only English alphanumeric chracters
only alphanumeric TextBox WPF C#,
sorry for my english.. but with this code for WPF, c#, I only permit alphanumeric
private void txtTraslado_TextChanged(object sender, KeyEventArgs e)
{
if (((e.Key < Key.NumPad0)||(e.Key > Key.NumPad9))&&((e.Key < Key.A)||(e.Key > Key.Z)))
{
e.Handled = true;
}
}
Use Asp.NET AJAX Control Toolkit
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
And Use FilteredTextBoxExtender
<asp:TextBox ID="txt_gpf_no" runat="server" CssClass="textbox"
MaxLength="10"></asp:TextBox>
<asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender_gpf_no" runat="server" Enabled="True"
TargetControlID="txt_gpf_no" FilterType="UppercaseLetters,LowercaseLetters,Custom" ValidChars="1234567890 ">
</asp:FilteredTextBoxExtender>
in my.Net Framework 4.5 C# application
private void txtRF_Register_Val_KeyDown(object sender, KeyEventArgs e)
{
//only enable alphanumeric
if (!(((e.KeyCode < Keys.NumPad0) || (e.KeyCode > Keys.NumPad9)) && ((e.KeyCode < Keys.A) || (e.KeyCode > Keys.E))))
{
e.SuppressKeyPress = false;
}
else
{
e.SuppressKeyPress = true;
}
}

Categories

Resources