IP Address in a MaskedTextBox?

前端 未结 6 1538
無奈伤痛
無奈伤痛 2020-12-03 15:09

How can I use a MaskedTextBox to prevent the user from entering an invalid IP address? (I want it to behave just like the Windows one).

6条回答
  •  感情败类
    2020-12-03 15:40

    Much simpler than the other answers:

    Use System.Net.IPAddress and System.Windows.Forms.MaskedTextBox

    set the following properties of the MaskedTextBox:

    MaskedTextBox.Mask = ###.###.###.###
    MaskedTextBox.ValidatingType = typeof(System.Net.IPAddress);
    

    whenever the text box is validating, event MaskedTextBox.TypeValidationCompleted is raised. The event arguments show the following:

    • Is the typed text acceptable as an IP address? (= does System.Net.IPAddress.TryParse return ok)
    • Description of the error as a string
    • The parsed value (= an object of System.NET.IpAddress
    • The type of the parsed value. Needed if you have several MaskedTextBoxes with different masks

    Upon receipt of this event you can decide whether to use the value or notify the user what is wrong with the value.

提交回复
热议问题