c# - How to create a masked TextBox for taking IP Address input?

C# - How to create a masked TextBox for taking IP Address input?

To create a masked TextBox for IP address input in C#, you can use various approaches. A common and straightforward method is to use a custom TextBox control with validation to ensure that the input conforms to the format of an IP address.

Example: Custom Masked TextBox for IP Address

Below is a step-by-step guide on how to create a simple masked TextBox for IP address input using Windows Forms.

1. Create a New Windows Forms Application

If you don't have an existing project, create a new Windows Forms Application project in Visual Studio.

2. Add the Custom TextBox Control

Create a new custom TextBox control to handle IP address formatting and validation. Here's a basic implementation:

using System; using System.Windows.Forms; using System.Net; public class IPAddressTextBox : TextBox { private const string IpAddressPattern = @"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; public IPAddressTextBox() { this.KeyPress += OnKeyPress; this.Leave += OnLeave; } private void OnKeyPress(object sender, KeyPressEventArgs e) { // Allow digits, dots, and control keys (backspace, delete) if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && !char.IsControl(e.KeyChar)) { e.Handled = true; } // Restrict to only three dots else if (e.KeyChar == '.' && (this.Text.Contains(".") && this.Text.Split('.').Length >= 4)) { e.Handled = true; } } private void OnLeave(object sender, EventArgs e) { ValidateIPAddress(); } private void ValidateIPAddress() { string text = this.Text.Trim(); if (string.IsNullOrEmpty(text) || !IsValidIPAddress(text)) { MessageBox.Show("Please enter a valid IP address.", "Invalid IP Address", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Focus(); } } private bool IsValidIPAddress(string text) { return IPAddress.TryParse(text, out _); } } 

3. Use the Custom Control in Your Form

Add the custom IPAddressTextBox to your form:

  1. Open your main form in the designer view.
  2. Add a UserControl to the form and place an instance of IPAddressTextBox onto it.

Alternatively, you can add the custom control programmatically:

using System; using System.Windows.Forms; public class MainForm : Form { private IPAddressTextBox ipAddressTextBox; public MainForm() { this.ipAddressTextBox = new IPAddressTextBox { Location = new System.Drawing.Point(10, 10), Width = 150 }; this.Controls.Add(this.ipAddressTextBox); this.Text = "IP Address Input Example"; this.ClientSize = new System.Drawing.Size(200, 100); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } 

Key Points

  1. KeyPress Event:

    • Filters input to allow only digits, dots, and control characters.
  2. Leave Event:

    • Validates the IP address when the control loses focus.
  3. Validation:

    • Uses IPAddress.TryParse to check if the input is a valid IP address.

Additional Enhancements

  • Formatting:

    • For more advanced formatting (e.g., auto-inserting dots), you might need to handle the TextChanged event and manipulate the text accordingly.
  • User Feedback:

    • You could add more user feedback features such as real-time validation or visual cues.

This approach provides a straightforward way to implement a masked TextBox for IP address input using Windows Forms in C#. If you're working with WPF or another UI framework, the concept is similar but with different control classes and events.

Examples

  1. Create a masked TextBox for IP Address input in Windows Forms C#

    • Description: Use the MaskedTextBox control to format IP address input in a Windows Forms application.
    • Code:
      using System; using System.Windows.Forms; public class MainForm : Form { private MaskedTextBox ipTextBox; public MainForm() { ipTextBox = new MaskedTextBox("000.000.000.000") { Location = new System.Drawing.Point(20, 20), Width = 150 }; Controls.Add(ipTextBox); } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  2. Implement IP Address validation in a masked TextBox in C#

    • Description: Validate IP address input using the TextChanged event of a MaskedTextBox.
    • Code:
      using System; using System.Net; using System.Windows.Forms; public class MainForm : Form { private MaskedTextBox ipTextBox; private Button validateButton; public MainForm() { ipTextBox = new MaskedTextBox("000.000.000.000") { Location = new System.Drawing.Point(20, 20), Width = 150 }; validateButton = new Button { Text = "Validate", Location = new System.Drawing.Point(20, 60) }; validateButton.Click += ValidateButton_Click; Controls.Add(ipTextBox); Controls.Add(validateButton); } private void ValidateButton_Click(object sender, EventArgs e) { if (IPAddress.TryParse(ipTextBox.Text, out _)) { MessageBox.Show("Valid IP Address"); } else { MessageBox.Show("Invalid IP Address"); } } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  3. Customize IP Address mask in TextBox using Regular Expressions in C#

    • Description: Use a TextBox with regex validation to handle IP address input.
    • Code:
      using System; using System.Text.RegularExpressions; using System.Windows.Forms; public class MainForm : Form { private TextBox ipTextBox; private Button validateButton; private Regex ipRegex; public MainForm() { ipTextBox = new TextBox { Location = new System.Drawing.Point(20, 20), Width = 150 }; validateButton = new Button { Text = "Validate", Location = new System.Drawing.Point(20, 60) }; validateButton.Click += ValidateButton_Click; ipRegex = new Regex(@"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); Controls.Add(ipTextBox); Controls.Add(validateButton); } private void ValidateButton_Click(object sender, EventArgs e) { if (ipRegex.IsMatch(ipTextBox.Text)) { MessageBox.Show("Valid IP Address"); } else { MessageBox.Show("Invalid IP Address"); } } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  4. Use a custom control for IP Address input in C#

    • Description: Create a custom TextBox control to handle IP address formatting.
    • Code:
      using System; using System.Windows.Forms; public class IpAddressTextBox : TextBox { protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); string[] parts = Text.Split('.'); if (parts.Length > 4) { Text = string.Join(".", parts, 0, 4); SelectionStart = Text.Length; } } } public class MainForm : Form { private IpAddressTextBox ipTextBox; public MainForm() { ipTextBox = new IpAddressTextBox { Location = new System.Drawing.Point(20, 20), Width = 150 }; Controls.Add(ipTextBox); } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  5. Handle IP Address input with TextBox and event validation in C#

    • Description: Use a regular expression and handle the TextChanged event to validate IP address input.
    • Code:
      using System; using System.Text.RegularExpressions; using System.Windows.Forms; public class MainForm : Form { private TextBox ipTextBox; private Regex ipRegex; public MainForm() { ipTextBox = new TextBox { Location = new System.Drawing.Point(20, 20), Width = 150 }; ipTextBox.TextChanged += IpTextBox_TextChanged; ipRegex = new Regex(@"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); Controls.Add(ipTextBox); } private void IpTextBox_TextChanged(object sender, EventArgs e) { if (ipRegex.IsMatch(ipTextBox.Text)) { ipTextBox.BackColor = System.Drawing.Color.White; } else { ipTextBox.BackColor = System.Drawing.Color.LightCoral; } } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  6. Create a masked input control for IP Address with Windows Forms in C#

    • Description: Implement a MaskedTextBox with a custom mask for IP address input.
    • Code:
      using System; using System.Windows.Forms; public class MainForm : Form { private MaskedTextBox ipTextBox; public MainForm() { ipTextBox = new MaskedTextBox { Location = new System.Drawing.Point(20, 20), Width = 150, Mask = "000.000.000.000" }; Controls.Add(ipTextBox); } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  7. Validate IP Address using a combination of MaskedTextBox and TextBox in C#

    • Description: Combine MaskedTextBox and TextBox to provide IP address input and validation.
    • Code:
      using System; using System.Net; using System.Windows.Forms; public class MainForm : Form { private MaskedTextBox ipMaskedTextBox; private TextBox ipTextBox; public MainForm() { ipMaskedTextBox = new MaskedTextBox("000.000.000.000") { Location = new System.Drawing.Point(20, 20), Width = 150 }; ipTextBox = new TextBox { Location = new System.Drawing.Point(20, 60), Width = 150 }; Controls.Add(ipMaskedTextBox); Controls.Add(ipTextBox); } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 
  8. Use TextBox with input validation for IP Address in WPF C#

    • Description: Create a WPF application with a TextBox and use input validation for IP address.
    • Code:
      using System; using System.Net; using System.Windows; using System.Windows.Controls; public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var ipTextBox = new TextBox { Width = 150 }; var validateButton = new Button { Content = "Validate", Width = 100 }; validateButton.Click += (s, e) => { if (IPAddress.TryParse(ipTextBox.Text, out _)) { MessageBox.Show("Valid IP Address"); } else { MessageBox.Show("Invalid IP Address"); } }; var stackPanel = new StackPanel(); stackPanel.Children.Add(ipTextBox); stackPanel.Children.Add(validateButton); Content = stackPanel; } } 
  9. Create a custom control for IP Address input in WPF C#

    • Description: Define a custom WPF control to handle IP address input.
    • Code:
      using System.Windows; using System.Windows.Controls; public class IpAddressControl : UserControl { private TextBox ipTextBox; public IpAddressControl() { ipTextBox = new TextBox { Width = 150 }; Content = ipTextBox; } public string IpAddress { get => ipTextBox.Text; set => ipTextBox.Text = value; } } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var ipControl = new IpAddressControl(); var validateButton = new Button { Content = "Validate", Width = 100 }; validateButton.Click += (s, e) => { if (IPAddress.TryParse(ipControl.IpAddress, out _)) { MessageBox.Show("Valid IP Address"); } else { MessageBox.Show("Invalid IP Address"); } }; var stackPanel = new StackPanel(); stackPanel.Children.Add(ipControl); stackPanel.Children.Add(validateButton); Content = stackPanel; } } 
  10. Implement IP Address validation with MaskedTextBox in WinForms C#

    • Description: Use MaskedTextBox with a custom mask and validate input to ensure it's a valid IP address.
    • Code:
      using System; using System.Net; using System.Windows.Forms; public class MainForm : Form { private MaskedTextBox ipTextBox; public MainForm() { ipTextBox = new MaskedTextBox("000.000.000.000") { Location = new System.Drawing.Point(20, 20), Width = 150 }; ipTextBox.Validating += IpTextBox_Validating; Controls.Add(ipTextBox); } private void IpTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e) { if (!IPAddress.TryParse(ipTextBox.Text, out _)) { e.Cancel = true; MessageBox.Show("Invalid IP Address"); } } [STAThread] public static void Main() { Application.EnableVisualStyles(); Application.Run(new MainForm()); } } 

More Tags

datacontext sdk c11 roguelike biopython tablecell iteration nosql-aggregation detox safearealayoutguide

More Programming Questions

More Electrochemistry Calculators

More Organic chemistry Calculators

More Retirement Calculators

More Other animals Calculators