0

I want to auto format a text entered in a textbox like so:

If a user enters 2 characters, like 38, it automatically adds a space. so, if I type 384052 The end result will be: 38 30 52.

I tried doing that, but it's ofr some reason right to left and it's all screwed up.. what I'm doing wrong?

static int Count = 0; private void packetTextBox_KeyPress(object sender, KeyPressEventArgs e) { Count++; if (Count % 2 == 0) { packetTextBox.Text += " "; } } Thanks! 
6
  • @SriramSakthivel Can you be more specific rather than just naming a control? I'm new to C#. I don't know the length, so I can't use a mask. Commented Sep 19, 2013 at 13:33
  • msdn.microsoft.com/en-us/library/… Commented Sep 19, 2013 at 13:37
  • @user2714359: Sriram gave you a hint and he didn't posted an answer so copying hit hint into a searchbox and read a little should not to much effort for you. Commented Sep 19, 2013 at 13:38
  • Yes, @wonko79 is right. Am just giving a hint. may be you're looking for MaskedTextBox but doesn't know the name of it. Commented Sep 19, 2013 at 13:43
  • Looks like you need n number of characters without any limit but with single space each for two characters? What will you do when user deletes a character using delete or backspace ? Commented Sep 19, 2013 at 13:44

4 Answers 4

1

It's much nicer if you just let the user type and then modify the contents when the user leaves the TextBox.

You can do that by reacting not to the KeyPress event, but to the TextChanged event.

private void packetTextBox_TextChanged(object sender, EventArgs e) { string oldValue = (sender as TextBox).Text.Trim(); string newValue = ""; // IF there are more than 2 characters in oldValue: // Move 2 chars from oldValue to newValue, and add a space to newValue // Remove the first 2 chars from oldValue // ELSE // Just append oldValue to newValue // Make oldValue empty // REPEAT as long as oldValue is not empty (sender as TextBox).Text = newValue; } 
Sign up to request clarification or add additional context in comments.

Comments

0

On TextChanged event:

 int space = 0; string finalString =""; for (i = 0; i < txtbox.lenght; i++) { finalString = finalString + string[i]; space++; if (space = 3 ) { finalString = finalString + " "; space = 0; } } 

Comments

0

I used

 int amount; private void textBox1_TextChanged(object sender, EventArgs e) { amount++; if (amount == 2) { textBox1.Text += " "; textBox1.Select(textBox1.Text.Length, 0); amount = 0; } } 

Comments

0

Try this.. on TextChanged event

textBoxX3.Text = Convert.ToInt64(textBoxX3.Text.Replace(",", "")).ToString("N0"); textBoxX3.SelectionStart = textBoxX3.Text.Length + 1; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.