Search code examples
c#textboxspacetextchanged

How to add space between bytes in textbox?


I have one textbox which gets only bytes and I want to add space between every bytes.

What I have done so far?

    public int a=0;
    public char c;
    private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
    {
        c = e.KeyChar;
    }
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        a = textBox2.TextLength % 3;
        if (c != 0x08 && a==2)
        {
            a = textBox2.TextLength % 3;
            int selectionIndex = textBox2.SelectionStart;
            textBox2.Text = textBox2.Text.Insert(selectionIndex, " ");
            textBox2.SelectionStart = selectionIndex + 1; // restore cursor position                
        }
    }

I add space with this code but if I delete some bytes it doesn't add space.

I think there is some issue in 'if' condition.

For example I write 'abcdef' it adds space and write

ab cd ef

then I delete 'cdef' and space it works properly in here. I write again 'cdef' it doesn't work and result will be like that

abcde f

How can I fix this issue?


Solution

  • I solve the problem with this code.

     private void textBox5_TextChanged(object sender, EventArgs e)
        {
            int selectionIndex = textBox5.SelectionStart;
            int chars = textBox5.Text.Length;
            int a = chars % 3;
            if (a == 2 && c!=0x08)
            { 
                textBox5.Text = textBox5.Text.Insert(selectionIndex, " ");
                textBox5.SelectionStart = selectionIndex + 1; // restore cursor position
            }
            if (chars > 1)
            {
                if (a == 0 && c == 0x08)
                {
                    textBox5.Text = textBox5.Text.Remove(chars - 1);
                    textBox5.SelectionStart = selectionIndex + 1;
                }
            }
        }