How to insert 12 consecutive digits into 4 text fields using the TextChanged property?

I am trying to insert (a combination of mouse or keyboard keys) a 12-digit number (IP address, but not the gap between them) into 4 fields. Each of them has a maximum length of 3.

I am trying to do this using TextChange, text field, property. I tried to use a substring, but not every octet works.

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(); } } 
+4
source share
4 answers

Try putting this code in the NextField method. And connect only to the txtF1 text field exchange 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:. Since you updated the question that there will be no dot character, you can split the line as follows

 var s1=Enumrable .Range(0,4) .Select(i => txt.Text.Substring(i * 3, 3)) .ToArray(); 
+4
source

This does not work as good as you try to change the text in the TextChanged handler - so it will fire again. Why not just handle the event handler in the next field when the length is 3, so you avoid a loop.

+2
source

Only works when pasted into TextF1.

 public PingIPRange() { InitializeComponent(); txtF1.TextChanged += new EventHandler(PasteNumbers); } private void PasteNumbers(object sender, EventArgs e) { if (txtF1.TextLength > 9) { txtF4.Text = txtF1.Text.Substring(9, 3); } if (txtF1.TextLength > 6) { txtF3.Text = txtF1.Text.Substring(6, 3); } if (txtF1.TextLength > 3) { txtF2.Text = txtF1.Text.Substring(3, 3); txtF1.Text = txtF1.Text.Substring(0, 3); } } 

To change, to be completely correct, you need to make min between (txtF1.TextLength - 9) and 3 in the Substring so as not to have problems with OutOfBound for txtF4, and the same for txtF3 and txtF2.

+1
source

You can use the KeyUp and MouseUp events for txtF1 and use the following code:

  private void txtF1_KeyUp(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.V) { PasteText(); } } private void txtF1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right && ((TextBox)sender).Modified) { PasteText(); } } private void PasteText() { string[] val = txtF1.Text.Split('.'); txtF1.Text = val[0].ToString(); txtF2.Text = val[1].ToString(); txtF3.Text = val[2].ToString(); txtF4.Text = val[3].ToString(); } 

NOTE. I did not enable error handling.

+1
source

Source: https://habr.com/ru/post/1386275/


All Articles