Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

c# - IP Address in a MaskedTextBox?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...