C# Input validation for a Textbox: float - c#

This supposedly easy task gave me some headache. I simply want to let the user enter any text that succeeds float.TryParse into a Textboxish control.
I could use a normal TextBox and check the Text in some btnOK_Click, but this is obviously lame. Also, there is a nice built-in MaskedTextBox control, but I failed to set it's mask to be equal to float.TryParse. Also, it seems to check for validity only when a focus change occurs.
Digging around on the net brought some interesting ideas, but none of them as nice as I would like.
How did you solve this problem? Did I simply miss an obvious solution, or do I have to implement this functionality myself?
I'm aware of a few similar threads on SO, but there was no feasible solution to be found.
Update: Yes, WinForms.

Edit
Well that makes it alot easier... Just add a Validating Event Handler to your textbox
and do the TryParse in the code behind. If its invalid, prompt the user as such.
Validating will fire when the user is finished typing and moves focus from the TextBox so if you need to do on the fly checking, you could handle the TextChanged or on of the KeyPress/KeyUp Event handlers instead
Original
Is this in asp.net or winforms/wpf
If its asp.net, you could use a combination of RegularExpressionValidator (to account for comma seperation, 1 decimal point, etc...) and a RangeValidator to set the min/max values for a float.
Aside from that, the only way to guarantee it would be to wrap the textbox in an updatepanel, stick a CustomServerValidator on it, and in the server validate function, do a TryParse on the TextBox.Text value, if it succeeds, IS VALID, if it fails, NOT VALID

Be careful using Validating and validating to false. You might find that, unless you enter valid data, you can't move focus off the textbox which is a really big usability pain.
I solve this by simply trying a TryParse() on LostFocus and if the TryParse fails I color the textbox background a reddish tint to make it obvious that something is wrong.

Related

Know which textBox has focus in xaml?

I have 3 textboxes that will change while it's being typed on a 4th one. I have tried the TextChanged="function" and change the content of the other three, but by chaging the .Text property, the event TextChanged is triggered again providing an undesired result. I was thinking of checking which textbox has the focus at the time, but I have no idea on how to implement that. I am experienced with Java and I'm very frustrated with all this c# and XAML. Thank you in advance.
If you search for FocusManager then you will find two kind of FocusManager class. But you have to go for
Windows.UI.Xaml.Input.FocusManager
not
System.Windows.Input.FocusManager.
It has static method GetFocusedElement() which queries the focus system to determine which object in the UI has focus.
There is a FocusManager-class, which might help you. Use the textbox' parent as scope-element.

Winforms disabling keyboard input on textbox but keeping textbox enabled

The scenario is like that;
I need to disable textbox to take input from user by keyboard. But textbox should take inputs using kind of devices like barcode reader. I thought to hold a timer and take the timespan between two key strokes (not clear yet). But maybe there is a property or smarter algorithm for that ?
p.s. it is a windows forms application.
You said you'll need to support any barcode reader, which usually emulate a keyboard, therefore there probably isn't an easy way to programmatically distinguish between input from a keyboard and a barcode reader.
Your idea about using timing is a good one, although I'd do something slightly differently. I'd add a Timer to the Form and start it when the first character is entered into the TextBox. The timer should be set to a very short time span and should have auto-restart disabled. When the timer goes off, check if the TextBox has a valid barcode, and if does, process it. Either way, clear the text box afterwards.
It would then appear to anyone attempting to use the keyboard that their typed text simply disappears, while a barcode scanner (which 'types' very fast) would still work.
Maybe you need to track 'keyboard press' event?
I don't think what automatically pasting something will trigger 'keyboard press' event.

CellValueChanged vs CellValidating Events for DataGridView

What's the best place to implement validation logic code and conditional formatting code for a DataGridView?
In a lot of books and articles that I've read on this control, it seems to suggest that the appropriate event to handle for this is the CellValidating one.
Well, the name more than implies this as well.
However, this event triggers a bit too often for my tastes and I'm not sure it is required.
For example, this event triggers everytimes the users switches to another row.
On the other hand, the CellValueChanged event seems to trigger only when the value of the cell changes, which means the validation code runs only when the value changes and not everytime a user changes cells.
Now, since so many books use the CellValidating event, I wonder if there is not any gotcha (in display for example) with using the CellValueChanged?
I understand that the impact in performance should be irrelevant when using simple validation and conditional highlighting rules but I would as much prefer it not to run useless code everytime the user moves to another cell if it can be avoided.
Thanks,
I'm using CellValueChanged currently on a grid with custom validation and have had no problems with display or anything else.
I used this event because I wanted to fire off a certain order of events, but only when the user changes the value of a cell.
I have not noticed much in the way of a performance hit (tested with 100 - 5000 rows).
I think in the end it depends on what your validation needs are. In my case, CellValueChanged has done what I wanted/needed.
EDIT
The biggest thing about the CellValidating event is that you can stop the user from leaving a cell, if the value entered does not pass your validation. I didn't want to do this.
Its simple, inside the CellValidatingEvent you need to check if a condition is right. If your condition is false then you just add this code e.cancel. It will prevent the cursor to lost its focus

Best way of validating/creating a number only text-box?

I am wanting to have a numbers/currency only textbox control.
So basically it should accept this kind of input
$123
523,100
$12.50
85.59
and convert this to
123
523100
12.50
85.59
and should not accept this input
F12
309$2342
,102
I have looked at validator controls but I would like to this conversion/checking completely from the client side. What would be the best way of doing this?
I also would like a clientside error(message box or something) popped up if they try to enter invalid data and prevent them from leaving the bad data in the textbox. and then when they get out of focus of the textbox it automatically converts the data into a flat number from the client side.
How would I get started in doing this? Is there something in ASP.Net that can help me? Would I need to just use the onfocus event or what event would be preferable from javascript to validate this? I'm rather inexperienced in Javascript also.. so I apologize if this is a bit noobish.
And yes, I will also validate on the server-side
You could try validating values inside a textbox using isNaN() to check if the value is a number, after each keystroke.
Anyways, this issue has been answered before here: Validate decimal numbers in JavaScript - IsNumeric()
Relying on client-side validation is a security risk if you need certain inputs rejected.
You could use the MaskedEditExtender or FilteredTextBox if you're using MS Ajax with your site. Otherwise there are lots of great javascripts out there to do client validation, especially for use with jQuery.
Just don't ignore validation on the server side.

Override tab behavior in WinForms

I have a UserControl that consists of three TextBoxes. On a form I can have one or more or my UserControl. I want to implement my own tab behavior so if the user presses Tab in the second TextBox I should only move to the third TextBox if the the second TextBox has anything entered. If nothing is entered in the second TextBox the next control of the form should get focus as per the normal tab behavior. If the user hasn't entered anything in the first or second TextBox and the presses tab there is this special case where a control on the form should be skipped.
By using the ProcessDialogKey I have managed to get it work kind of ok but I still have one problem. My question is if there is a way to detect how a WinForms control got focus since I would also like to know if the my UserControl got focus from a Tab or Shift-Tab and then do my weird stuff but if the user clicks the control I don't want to do anything special.
As a general rule, I would say overriding the standard behavior of the TAB key would be a bad idea. Maybe you can do something like disabling the 3rd text box until a valid entry is made in the 2nd text box.
Now, having said this, I've also broken this rule at the request of the customer. We made the enter key function like the tab key, where the enter key would save the value in a text field, and advance the cursor to the next field.
I don't think there's a built-in way that you could do it. All of the WinForms focus events (GotFocus,LostFocus,Enter,Leave) are called with empty EventArgs parameters, which will not give you any additional information.
Personally, I would disable the third textbox, as Rob Thomas said. If you're determined to do this, though, it wouldn't be difficult to set up a manual (read: hackish) solution. Once the tab key is pressed (if the focus is on the second textbox), set a variable inside your form. If the next object focused is then the third textbox, then you know exactly how it happened.
The reason for this odd tab behavior is all about speed in the input process. It was really good to get some input, I hadn't thought about disabling a textbox but that could actually work. But using the Enter key to accept the input hadn't even crossed my mind. That will work so much better. The user can enter the numbers and then press enter to accept the input and the next possible textbox will be the active one. It's like having the cake and eating it too, The speed factor is there since when using the enter key no unnecessary tabing must be done to get to the correct field and using the enter key next to the numeric keyboard makes it really smooth.
Thanks for the input!
I agree with DannySmurf. Messing with the tab order might give you hell later on if the requirements for the application change.
Another thing that you could do is to implement some kind of wizard for the user to go through.
Better than disabling controls, try monkeying around with TabStop - if this is false, the control will be simply skipped when tabbing.
I'd also suggest that the Changed event of the TextBox is the place to be updating TabStop on the other controls.
I've done something similar to this with a login control, where users could enter either a username or an email address (in separate fields), plus their password, and tabStop is what I used to get the job done.

Categories