Search code examples
c#winformstextboxseparator

Creating a character separator for a textbox


I am doing some more preparation for the university and am sort of stuck now. I am trying to make hexadecimal values in a textbox be outlined using dashes('-') while I am typing thus it should be done dynamically.

To be a bit more precise here are some pictures of what I am trying to do:

If I am typing hexes like this:

image1

I want them to get separator dashes while I am typing them:

image2

So far I have tried doing it with a for loop and I think that it should have worked out but it doesn't print out my values but rather just the dashes sans the text.

Here is the code bit:

   int i = 0;
        private void inputBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (hexRadioButton.Checked)
            {
                if (!char.IsControl(e.KeyChar))
                {
                    if (i < 2)
                    {
                        i++;
                        e.Handled = true;
                    }

                    else
                    {
                        i = 0;
                        inputBox.AppendText("-");
                        e.Handled = true;
                    }
                }
            }
    }

Solution

  • One approach would be to validate the whole string any time the text changes. This will account for pasting text as well as typing. It's a little brutish, but for a relatively short string it should do the job:

    private void inputBox_TextChanged(object sender, EventArgs e)
    {
        if (hexRadioButton.Checked)
        {
            var allowedValues = new[] 
            {
                'A', 'B', 'C', 'D', 'E', 'F',
                'a', 'b', 'c', 'd', 'e', 'f',
                '1', '2', '3', '4', '5', '6',
                '7', '8', '9', '0', '-'
            };
    
            var validString = new StringBuilder();
            var validChrIndex = 1;
    
            for (int i = 1; i <= inputBox.TextLength; i++)
            {
                var chr = inputBox.Text[i - 1];
    
                if (!allowedValues.Contains(chr)) continue;
    
                if (validChrIndex % 3 == 0)
                {
                    if (chr != '-')
                    {
                        validString.Append('-');
                        validChrIndex++;
                    }
                }
                else if (chr == '-')
                {
                    continue;
                }
    
                validString.Append(chr);
                validChrIndex++;
            }
    
            if (!validString.ToString().Equals(inputBox.Text))
            {
                inputBox.Text = validString.ToString();
                inputBox.SelectionStart = inputBox.TextLength;
            }
        }
    }