Answered Only one word in a text box

lional

Well-known member
Joined
Nov 29, 2018
Messages
55
Programming Experience
Beginner
Hi
I am trying to prevent the user from inputting or pasting more than one word in a text box.
Which would be the best way to accomplish this. I was thinking of creating a keypress event forbidding spaces but not sure if this will cater for pasting text as well.

I am creating a form for firstname, middlename, and lastname and I only want one name in the firstname column so that users don't input the firstname and middlename in the firstname textbox

Thankyou in advance

Have a great day
 
If you want to avoid pasting too then you'd need a custom control and to override the WndProc method to filter the WM_PASTE (I think) message. It's possible to do but it would be easier to simply validate after the fact. You could even automatically move anything after the first space into the second control.
 
Thank you. Is it possible to validate the textbox when they tab or move to the next control rather than at the end of the form
 
Thank you. Is it possible to validate the textbox when they tab or move to the next control rather than at the end of the form
That's exactly how it should be done. You can handle the Validating event and set e.Cancel to True to prevent the control losing focus if it contains invalid data. If you don't want to prevent that loss of focus then you can handle the Leave event instead.
 
Thank you. I will research how to accomplish that. Still fairly new to OOP, C# and WPF. Thank you for your assistance
 
Thread moved from C# forum to WPF forum, choose a more specific forum over a general one.
 
Still fairly new to OOP, C# and WPF. Thank you for your assistance
Ah, you didn't mention that this is for WPF. I assumed WinForms, which you will find that most people do if you don't specify otherwise. There is a forum dedicated to WPF, although there is one for WinForms and you didn't post there either. You did say KeyPress event though, which exists in WinForms but not WPF. Can you confirm that you definitely are using WPF?
 
I am using wpf. sorry I used to do winforms busy doing my first wpf app learning as I go. How would I verify the control when moving to another one. Just point me in the right direction so that I can research. The best way to learn
 
No, I am not. Is there an event to check for when I am exiting a control and moving onto another one
 
Ah! So you are using WPF, but using it as if it was WinForms with a lot of code behind.
 
I wrote the app a while ago using winforms for a college as a freebie as a training exercise for me. I then studies a bit on OOP and then redid it as WPF again as a project for me to learn on. It will get revised frequently as my knowledge grows. As I become more proficient it will be revised
 
Here's the WPF MVVM along with try to do as much as possible in XAML approach to validation:
 
Back
Top Bottom