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();
}
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With