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
Related
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.
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.
I have two textbox to let user input start date and end date. Then I have a checkbox that allow user to check to see some calculations. My question is, how can I disable the checkbox if the duration between start date and end date is shorter than a specific length. I mean, right after user input the start date and end date, he/she would see the checkbox is disabled because the time period length is not long enough.
if (productWealth.Count < 3)
checkBox7.Enabled = false;
This is what I have now, if count < 3, then checkbox 7 is disabled. Seems like the application only run the count when run click the RUN button, but I want them to see immediate effect.
You can use the event TextChanged, so when the user change the value of the TextBox you check if its true and enable the CheckBox.
tboxEndDate.TextChanged += new TextChangedEventHandler(tboxEndDate_TextChanged);
void tboxEndDate_TextChanged(object sender, TextChangedEventArgs e)
{
// Calcule the productWealth
if (productWealth.Count < 3) checkBox7.Enabled = false;
}
Look at the Leave() event for your start and end date textboxes. Place your if() statement in there.
Uh that is, if this is WinForms...
I have two textbox's. I have an event setup for the "onLostFocus" of the textbox's. If i finish typing a word into both boxes one after the other all is well. At the point where i click back on the first textbox i want to click halfway through the word (perfectly resonable thing for a user to do). When the onLostFocus event fires here is my code :
void tbox_LostFocus(object sender, RoutedEventArgs e)
{
IInputElement focusedelement = FocusManager.GetFocusedElement(this);
if (focusedelement is TextBox)
{
TextBox focusedTextBox = focusedelement as TextBox;
int focusIndex = m_commandsStacker.Children.IndexOf(focusedTextBox);
int caretIndex = focusedTextBox.CaretIndex;
The caret index returns as 0 when i call focusedTextBox.CaretIndex. At that point I need to refresh the whole form and set parameters and all other kinds of whizzery, storing the texbox index and caret position to put everything back the same. Why does it return 0 and not the position where the caret should be halfway between the word?
This just doesn't work in c# express edition 2008 (whatever version of WPF that is) so the best thing to do here is to switch to onTextChanged and run the exact same code there, which works a treat. Its obviously annoying that you have to run the code multiple more times than if it worked on lost focus. When I get the time I will check if it works in c# express 2010 as we are upgrading (eventually)
Using Windows Mobile 6.5 and C#
The CharacterCasing property seems to be missing from WinMo 6.5 and I decide to just catch the textchanged event and set the text with ToUpper.
This works - but on every keypress, it sends the cursor back to the beginning of the string, not the end.
I know this is old, but hopefully this can help somebody else. I implemented the KeyPress event like the following.
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = Char.ToUpper(e.KeyChar);
}
Ritu, just to comment on your answer. You should keep in mind that this might be confusing for a user if the user has positioned the caret in the middle of the string to perform some edit and then the caret jumps to the end of the string on the key press.
An alternative might be to change the text to upper case when the edit control loses focus.
Try here such implementation.
public MainForm()
{
InitializeComponent();
InitializeUpperCaseTextBox();
}
private void InitializeUpperCaseTextBox()
{
txtbox.CharacterCasing = CharacterCasing.Upper;
//... etc.
}
The soluttion of setting the text position to the end of the string seems like would be a hassle if you ever need to edit text that you have already entered.
It's been a while since I thought about the C# event model but, one alternative might be to catch the KeyPress event and change any lowercase KeyChar values to uppercase before passing them on to the next handler.
The way you are approaching seems to be wrong.
There are so many different ways to insert data into that textbox. What about copy & paste for instance?
Just perform a .Text.ToUpper() when accessing the value of the Textbox
Save the SelectionStart and SelectionLength before changing the text. The ToUpper should make no changes to the length, so you can simply set the SelctionStart and SelectionLength back to what they had been.
Also, I would expect to get a changed event again when you set it ToUpper. I'm not sure if you also need to check that the ToUpper actually changed anything before you set Text again. It may be smart enough to check that for you when you assign the text and avoiding giving you an infinite recursive loop of change events. However, you probably don't want to alter the selection in the event handler call for the case where you aren't making a further change, only in the outer call where you are assigning back to Text. So you might as well guard recursion directly.
Something like:
bool m_InMyTextChanged = false;
private void txtMyText_TextChanged(object sender, EventArgs e)
{
if (m_InMyTextChanged)
return; // Recursive! We can bail quickly.
m_InMyTextChanged = true; // Prevent recursion when we change it.
int selectionStart = txtMyText.SelectionStart;
int selectionLength = txtMyText.SelectionLength;
string originalText = txtMyText.Text;
string newText = originalText.ToUpper();
if (newText != originalText)
{
txtMyText.Text = newText; // Will cause a new TextChanged event.
// Set the selection back *after* the assignment, which has reset them.
txtMyText.SelectionStart = selectionStart;
txtMyText.SelectionLength = selectionLength;
}
m_InMyTextChanged = false; // Allow it for next time.
}
could work. I haven't worked in Windows Mobile, but I would think this would work the same as in general for .NET.
I figured it out. So on the textChanged event, I replace the entered text with the ToUpper version. Then I set the SelectionStart property to the Text.Length to move the cursor to the end.