Hi i want to make textbox to enter mac adress and every 2 characters i want to automaticly add ':'
I wanted to use TextChanged event
private void MacAdressTextBox_TextChanged(object sender, TextChangedEventArgs e) {
if (MacAdressTextBox.Text.Length > 2)
MacAdressTextBox.Text += ":";
}
here i am adding : after 2 characterrs entered but after those 2 characters the app frezes ... have no idea why any help?
When the text changes MacAdressTextBox_TextChanged is triggered.
In MacAdressTextBox_TextChanged you change the text.
see step 1
your text change causes an infinite recursion on MacAdressTextBox_TextChanged.
One way to do it would be to grab the Text, remove the colons, then add them back in at the correct positions. In order to keep the app from hanging in an endless recursive loop, you can add a variable to track whether or not the text is being changed by our code or the user.
For example:
// When this is true it means our code is changing the text
private bool updatingTextWithCode = false;
private void MacAdressTextBox_TextChanged(object sender, EventArgs e)
{
if (updatingTextWithCode)
{
// Our code is doing the update, so just reset the variable
updatingTextWithCode = false;
}
else
{
// The user is updating the text, so process the contents
var newText = "";
// Store the mac address without the ':' characters
var plainText = MacAdressTextBox.Text.Replace(":", "");
// Then add ':' characters in correct positions to 'newText'
for (int i = 1; i <= plainText.Length; i++)
{
newText += plainText[i - 1];
if (i % 2 == 0) newText += ":";
}
// Set our global variable and update the text
updatingTextWithCode = true;
MacAdressTextBox.Text = newText;
MacAdressTextBox.Select(MacAdressTextBox.TextLength, 0);
}
}
UPDATE: CodeCaster correctly pointed out that this code does not allow the user to backspace over a colon. One way to fix this is to add the following event handler as well:
private void MacAdressTextBox_KeyDown(object sender, KeyEventArgs e)
{
// Disable formatting code when backspacing
if (e.KeyCode == Keys.Back) { updatingTextWithCode = true; }
}
Related
I am making a simple email sender and what I want to do is to check if the textbox.text has 14 characters. If it's 14 - then text turns to green, if less it turns to red. I've encountered a problem when I type 14th character. It doesn't turn green. It does when I type another character which is not shown since I have MaxLength = 14, but I still need to type in that 15th character. Also when I try deleting characters, the string doesn't turn red with the first deleted char, but after a few. I've tried things like Regex and trim() thinking that there might be some special characters but it doesn't seem to work. I also recorded a video with the issue to make it more describing.
private void trackBox1_KeyPress(object sender, KeyPressEventArgs e)
{
trackBox1.Text = RemoveSpecialCharacters(trackBox1.Text);
trackBox1.Text = trackBox1.Text.Replace("\r\n", "\n");
errorBox.Text = trackBox1.TextLength.ToString();
if (trackBox1.TextLength < 14)
{
trackBox1.ForeColor = Color.Red;
} else if (trackBox1.TextLength == 14)
{
trackBox1.ForeColor = Color.Green;
}
trackBox1.Text.TrimEnd();
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}
Instead of using the trackBox1_Keypress put your if statement in the trackBox1_TextChanged event and to count the length of the text you should use trackbox.Text.Length instead of trackbox1.TextLength
Here is a sample snippet int the TextChanged event that changes the color from red to green if the text length is greater than or equal to 14.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length <= 14)
{
textBox1.ForeColor = Color.Red;
}
else
{
textBox1.ForeColor = Color.Green;
}
}
Im not sure if trackBox1.TextLength is the proper way to get the length
trackBox1.Text.Length //try this
//and also your event
private void yourTextBox_TextChanged(object sender, EventArgs e)
{
}
Have a look at the Control.KeyPress docs... the event fires after a key has been pressed, but before the character actually enters the textbox. This means that the length you're checking is one less than the length you were expecting (unless the key just pressed was backspace, which KeyPress also catches, in which case it is one greater than the length you were expecting).
In a Windows Forms App, I want to select all the text in a text box with txtBox.SelectAll() as the code for the text box but after I debug it I can only type ONE letter in the textbox that is selected. The letter keeps changing as I type. How do I write more than one letter that is selected?
private void TextBox1_TextChanged(object sender, EventArgs e)
{
txtBox.SelectAll();
}
When you call txtBox.SelectAll() in your code, all the text is selected. Than, when you type another character, the default (and expected) behavior is to overwrite the selection, so you end up only with the new character.
You can override this behavior with this code (see note below):
// Backup field for textBox1.Text
string _textBox1TextBkp = "";
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Add the new characters to backup field
_textBox1TextBkp += textBox1.Text;
// If textBox1.Text is empty:
if(textBox1.Text == "")
{
if (_textBox1TextBkp.Length > 0)
{
// Option 1: Remove last character
_textBox1TextBkp = _textBox1TextBkp.Remove(_textBox1TextBkp.Length - 1);
// Option 2: Delete all text - clear backup field
//_textBox1TextBkp = "";
}
}
// Set textBox1.Text to the backup field if needed
if (_textBox1TextBkp != textBox1.Text)
{
// Remove TextChanged event before modifying the text.
// This avoid stack-overflow by triggering the event when still inside.
textBox1.TextChanged -= textBox1_TextChanged;
// Set textBox1.Text to the backup field
textBox1.Text = _textBox1TextBkp;
// Add the removed event
textBox1.TextChanged += textBox1_TextChanged;
}
// Call SelectAll
textBox1.SelectAll();
}
when deleted a character (Backspace), you have two options in this code:
Option 1: Remove last character.
Option 2: Delete all text.
Note: the code assumes that when deleted a character (Backspace), all text is selected and the text-box is cleared. If all text is not selected, its more complicated and I did not deal with that.
i made code to format number when total lengh is == 11, it run on texbox change, but only format when it have 11 characters, i would like to make it on runtime (live), understood ? Its possible ? See my code:
private void textBox3_TextChanged(object sender, EventArgs e)
{
Int64 cpf = Convert.ToInt64(textBox3.Text);
if (textBox3.TextLength == 11)
{
textBox3.Text = string.Format(#"{0:000\.000\.000-00}", Convert.ToInt64(cpf));
}
}
Thanks
As lazyberezovsky stated, use a masked textbox, but set the PromptChar to whatever you want. Something along the lines of:
//In your form_load
//Based on your code above, assuming textBox3 is a MaskedTextbox
textBox3.KeyUp += CheckEvent()
textBox3.Mask = "000000000000";
textBox3.PromptChar = 'x'; //set this to a space or whatever you want ' ' for blank!
//check AFTER every key press
private void CheckEvent(object Sender, KeyEventArgs e)
{
if(textBox3.Text.Count() < 12)
{
return;
}
//change the textboxMask when all chars present
maskedTextBox1.Mask = "0:000.000.000-00";
}
Consider to use MaskedTextbox with Mask equal to 000.000.000-00. It will fill mask in usual way from left to right. Input will look like:
___.___.___-__
When use types 1 it will show 1__.___.___-__.
When use types 12 it will show 12_.___.___-__. And so on.
I wonder if there is better way of validating text box than using KeyDown event. The reason for this is that my event isn't reacting when it should. For example, in following code check works perfect. I can start typing characters and until 6 or more is entered I am being displayed that I must type at least 6 characters. The problem is that when I type 6 characters and then remove one, making it 5 characters; it doesn't display the error. Only when I remove more than 2 characters it display my error.
How can I avoid this, or what else I could use to do the check on the fly?
public AuthenticationWindow()
{
InitializeComponent();
// Setting up a password character.
// We are trying to hide what text user is typing.
txtPassword.PasswordChar = char.Parse("-");
txtPassword.MaxLength = 20;
txtUserName.MaxLength = 20;
txtPassword.KeyDown += KeyDownCheck;
}
protected void KeyDownCheck(object sender, KeyEventArgs e)
{
bool validPass = txtPassword.Text.Length < 6;
if (validPass)
lblMessage.Text = "Password can not be shorter than 6 characters!";
else
lblMessage.Text = "Password is valid.";
}
You should use the TextChanged event instead.
textBox1.TextChanged += new EventHandler(txtPassword_TextChanged);
private void txtPassword_TextChanged(object sender, EventArgs e) {
bool validPass = txtPassword.Text.Length < 6;
if (validPass)
lblMessage.Text = "Password can not be shorter than 6 characters!";
else
lblMessage.Text = "Password is valid.";
}
I have a WPF C# program where I attempt to delete certain characters from a text box at TextChanged event. Say, for instance, the dollar sign. Here is the code I use.
private void txtData_TextChanged(object sender, TextChangedEventArgs e)
{
string data = txtData.Text;
foreach( char c in txtData.Text.ToCharArray() )
{
if( c.ToString() == "$" )
{
data = data.Replace( c.ToString(), "" );
}
}
txtData.Text = data;
}
The problem I have is that whenever the user enters $ sign (Shift + 4), at the TextChanged event it removes the $ character from the textbox text alright, but it also moves the cursor to the BEGINNING of the text box which is not my desired functionality.
As a workaround I thought of moving the cursor the the end of the text in the text box, but the problem there is that if the cursor was positioned at some middle position then it would not be very user friendly. Say, for instance the text in the textbox was 123ABC and if I had the cursor after 3, then moving the cursor to the end of the text would mean that at the next key stroke user would enter data after C, not after 3 which is the normal functionality.
Does anybody have an idea why this cursor shift happens?
Its not an answer to your question, but probably a solution for your problem:
How to define TextBox input restrictions?
If it is overkill for you, set e.Handled = true for all characters you want to avoid in PreviewKeyDown (use Keyboard.Modifiers for SHIFT key) or PreviewTextInput.
Try TextBox.CaretIndex for restoring cursor position in TextChanged event.
Hope it helps.
You can use the Select function of TextBox to change the cursor position.
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
textBox1.Text = textBox1.Text.Replace("$", "");
textBox1.Select(textBox1.Text.Length, 0);
}
You can see more about Position the Cursor on the MSDN
You can use the SelectionStart property of the textbox. Probably something along these lines should work:
private void txtData_TextChanged(object sender, TextChangedEventArgs e)
{
var pos = txtData.SelectionStart;
string data = txtData.Text.Replace("$", "");
txtData.Text = data;
txtData.SelectionStart = pos;
}
You can try Regular Expression
Sample
1) Use PreviewTextInput="CursorIssueHandler" in .xaml file
2) In your .cs file ,write the below code:
private void CursorIssueHandler(object sender, TextCompositionEventArgs e)
{
var TB = (sender as TextBox);
Regex regex = new Regex("[^0-9a-zA-Z-]+");
bool Valid = regex.IsMatch(e.Text);
//System.Diagnostics.Debug.WriteLine(Valid); // check value for valid n assign e.Handled accordingly your requirement from regex
e.Handled = Valid;
}