only enter specific characters in to a textBox - c#

I want to enter 2 decimal number to a textBox. I am using the below code which I have found in the internet in the keypress event of the textBox.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
// only allow two decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -2))
{
e.Handled = true;
}
In the above code first if condition id working well and I can only input numbers. But the second part which restricts only 2 decimals is not working. Please tell me what is wrong in this code.
Thank you.

Never use KeyPress for such validations. You will have always problems with some tricky editions such as replacing selected text, pasting something from the clipboard, etc.
Use Validating event instead or just do some custom validation when the user clicks the OK button or whatever. In these cases you can assume that the user has finished the edition and you can always validate the final text.
If the user has to enter some strict-length text, you can use MaskedTextBox instead.

Related

C# Masked textbox with date format skips first character

I have a problem in a winform app.
I have several masked textbox which use the short date mask (//____), the problem is that if I select all the text (either with Ctrl + a or from code) and I write a new date is like that the first character goes at an 11th position (the mask disappear and i see only the character I wrote) and if I press backspace the text becomes something like this _1/01/1979 and I have to select all again and press backspace or delete everything.
I handled in this way
private void maskedTxt_KeyPress(object sender, KeyPressEventArgs e)
{
MaskedTextBox msk = sender as MaskedTextBox;
if (msk != null)
{
if (!string.IsNullOrEmpty(msk.Text.Replace("/", string.Empty).Replace(":", string.Empty).Trim()) && _focused)
{
_focused = false;
SendKeys.SendWait("{BACKSPACE}");
}
}
}
_focused is a Boolean variable that I set to true if a validation error happens at the leave event of the masked textbox (invalid date, the date is too big or too small etc...)
so that when someone enters the textbox the text can be written correctly
Is there a better way to handle this "error" or this is good? I tried it and it worked but a lot of people will have to use this application and probably there will be some errors along the way.
Thanks

C# Winforms - Display Tooltip over textbox when mouse not over it

I am working on a project in Visual Studio 2017, using Winforms and C#. I have created a textbox which accepts only certain characters, and I would like it to display a bubble tooltip saying "Only letters and numbers are allowed" whenever a user enters an invalid character. I have managed to display a tooltip:
//titleInput - The textbox.
//characterWarning - the tooltip.
private void TitleInputKeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsLetter(e.KeyChar) && !Char.IsNumber(e.KeyChar) && !Char.IsWhiteSpace(e.KeyChar) && !Char.IsControl(e.KeyChar)) //Check if character is invalid.
{
characterWarning.SetToolTip(titleInput, "Only letters and numbers are allowed"); //Display the tooltip.
e.Handled = true; //
}
}
But it is shown only if the mouse is over the textbox, and if the textbox is in focus. How do I make a tooltip show over a textbox even if the mouse is not over the control? Thanks in advance.
You can use Tooltip control on the form, you can do it like this:
ToolTip1.Show("Text to display", Control)
Check this link for reference.
Consider using System.Windows.Forms.ToolTip.Show Method instead.

Switch after 5 characters

I'm trying to swipe a card and after the 5 characters are entered I want it to go to the next textfield. I'm scanning a card.
Currently I have:
private void membernumber1_TextChanged(object sender, EventArgs e)
{
}
But this changes it right after it enters one character, is there anyway to make it switch after 5 characters entered?
Just count the number of characters in the Text property. Using a counter won't work if they use the backspace key.
if( membernumber1.Text.Length == 5 )
SwitchFocus();
Be aware though that this may not work for text that was pasted into the control (i.e., if it was > 5 characters). You'll need proper validation for that case or you can just disable pasting, but validation is preferable as there are certainly other restrictions like being all numeric.

Why are some textboxes not accepting Control + A shortcut to select all by default

I have found a few textboxes here and there in my program that accepts Control+A shortcut to select the entire text "by default" with "no coding".
I don't know what additional information I have to give here to enable it for all of them, as I find absolutely no difference between these textboxes. They are all simple dragged and dropped textboxes.
Note: I'm not talking about this piece of code:
if (e.Control && e.KeyCode == Keys.A)
{
textBox1.SelectAll();
}
I want selection by default... or is there anyway to change textbox property so that textboxes accept all default windows shortcuts?
Everything else (Control + Z, Control + X, Control + C, Control + V) works by default! Why not Control + A?
Update: The text boxes that accepted Ctrl+A by default were masked textboxes, not the regular one. And at that point I was with .NET 2.0. But I guess the original problem was something else, as I can see Ctrl+A working fine by default in .NET 2.0 code.
You might be looking for the ShortcutsEnabled property. Setting it to true would allow your text boxes to implement the Ctrl+A shortcut (among others). From the documentation:
Use the ShortcutsEnabled property to
enable or disable the following
shortcut key combinations:
CTRL+Z
CTRL+E
CTRL+C
CTRL+Y
CTRL+X
CTRL+BACKSPACE
CTRL+V
CTRL+DELETE
CTRL+A
SHIFT+DELETE
CTRL+L
SHIFT+INSERT
CTRL+R
However, the documentation states:
The TextBox control does not support the CTRL+A shortcut key when the Multiline property value is true.
You will probably have to use another subclass of TextBoxBase, such as RichTextBox, for that to work.
Indeed CTRL + A will not work unless you add something like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.A))
{
if (sender != null)
((TextBox)sender).SelectAll();
e.Handled = true;
}
}
This answer worked for me in a similar question (which isn't marked as accepted)
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
var keyCode = (Keys) (msg.WParam.ToInt32() &
Convert.ToInt32(Keys.KeyCode));
if ((msg.Msg == WM_KEYDOWN && keyCode == Keys.A)
&& (ModifierKeys == Keys.Control)
&& txtYourTextBox.Focused)
{
txtYourTextBox.SelectAll();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Original Post: How can I allow ctrl+a with TextBox in winform?
Make sure that
Application.EnableVisualStyles();
is not commented out in
static void Main()
That can disable Ctrl+A
This question wants an answer that cannot be given in the form of code avoidance, as the Win32 API at the core of the other methods doesn't allow it. If other methods DO allow it, they are just writing the code for you. :)
So the real question is: What is the smallest, neatest way to do it? This worked for me:
First, there is no need to handle WM_KEYDOWN! And no need to test for the Ctrl key already down either. I know that most examples here (and CodeProject and many other places) all say there is, but it does not cure the beep that results whenever a WM_CHAR arises that is not handled.
Instead, try handling WM_CHAR and doing the Ctrl+A selection there:
LRESULT CALLBACK Edit_Prc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam){
if(msg==WM_CHAR&&wParam==1){SendMessage(hwnd,EM_SETSEL,0,-1); return 1;}
else return CallWindowProc((void*)WPA,hwnd,msg,wParam,lParam);
}
Remember to subclass the EDIT control to this Edit_Prc() using WPA=SetWindowLong(...) where WPA is the window procedure address for CallWindowProc(...)

C# textbox deletion question

I am working on a project that I use textbox as telnet terminal.
The terminal has "->" as the command prompt in the textbox.
Is there a way to disable the delete or backspace once it reach the "->" prompt?
I don't want to delete the command prompt.
Thanks
Dave is right.
The best way to do this is to make a label on the left side of the textbox that says ->.
You can remove the textbox's border and put them both in a white (or non-white) box to make it look real.
This will be much easier for you to develop and maintain, and will also be more user-friendly. (For example, the Home key will behave better)
Two options:
Make the prompt ("->") an image or label, instead of being part of the textbox.
If it's a web app, handle the textchanged event in javascript and cancel the textchanged if it represents a deletion of the prompt. If its not a web app, do the same thing in c# rather than JS.
You could always make sure that when deleting, the index of the character you're deleting is > 1 (since -> would occupy positions 0 & 1)
This is a naive example, but you should be able to figure it out from here. You can peak at the keydown event and cancel it, when desired.
private void testTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back && testTextBox.SelectionStart == 2)
{
e.SuppressKeyPress = true;
}
}

Categories