Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste 12 consecutive digit numbers into 4 text boxes using TextChanged property?

Tags:

c#

winforms

I am trying to be able to paste (mouse or keyboard shortcut) a 12 digit number (IP address, but no periods between) into 4 fields. Each has maximum length of 3.

I am trying to do this by using TextChange, text box, property. I was trying to use Substring but it doesn't each octet work.

    public PingIPRange()
    {
        InitializeComponent();

        txtF1.TextChanged += new EventHandler(NextField);
        txtF2.TextChanged += new EventHandler(NextField);
        txtF3.TextChanged += new EventHandler(NextField);
    }

    private void NextField(object sender, EventArgs e)
    {
        if (txtF1.TextLength == 3)
        {
            txtF2.Focus();
            txtF1.Text = txtF1.Text.Substring(0, 3);
            txtF2.Text = txtF1.Text.Substring(3, 30);
        }
        if (txtF2.TextLength == 3)
        {
            txtF3.Text = txtF2.Text.Substring(3, 27);
            txtF3.Focus(); 
        }
        if (txtF3.TextLength == 3)
        {
            txtF4.Focus();
        }
    }
like image 599
NewHelpNeeder Avatar asked Feb 23 '23 03:02

NewHelpNeeder


2 Answers

Try putting this code in NextField method. And hookup only to txtF1 textbox textchange event.

TextBox txt = (TextBox) sender; 
var s1 = txt.Text.Split('.');

if(s1.Length==4)
{
    txtF1.Text = s1[0];
    txtF2.Text = s1[1];
    txtF3.Text = s1[2];
    txtF4.Text = s1[3];
} 

UPDATE: As you have updated the question that there will not be any dot symbol you can split string like this

var s1=Enumrable
    .Range(0,4)
    .Select(i => txt.Text.Substring(i * 3, 3))
    .ToArray();
like image 115
Maheep Avatar answered Feb 24 '23 16:02

Maheep


This wont work so well as you're trying to change text within the TextChanged handler - so it will fire itself again. Why not just have the event handler change focus to the next box when the length is 3, that way you avoid a cyclic loop.

like image 21
Paul Avatar answered Feb 24 '23 17:02

Paul