C# TextBox 控件限制输入IP地址:使用正则表达式验证
要限制textBox控件只允许输入IP地址,可以使用正则表达式来验证输入。以下是一个示例代码:\n\ncsharp\nusing System;\nusing System.Text.RegularExpressions;\nusing System.Windows.Forms;\n\nnamespace IPAddressTextBoxExample\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n {\n // 只允许输入数字、小数点和退格键\n if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))\n {\n e.Handled = true;\n }\n\n // 小数点只能输入一次\n if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))\n {\n e.Handled = true;\n }\n }\n\n private void textBox1_Leave(object sender, EventArgs e)\n {\n // 验证输入的IP地址格式是否正确\n string ipAddress = textBox1.Text;\n if (!IsIpAddress(ipAddress))\n {\n MessageBox.Show("请输入有效的IP地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);\n textBox1.Focus();\n }\n }\n\n private bool IsIpAddress(string ipAddress)\n {\n // 使用正则表达式验证IP地址格式\n Regex regex = new Regex(@"^(?:[0-9]{1,3}.){3}[0-9]{1,3}$");\n return regex.IsMatch(ipAddress);\n }\n }\n}\n\n\n在上面的示例代码中,textBox1_KeyPress事件处理程序用于限制只能输入数字、小数点和退格键。textBox1_Leave事件处理程序用于验证输入的IP地址格式是否正确。IsIpAddress方法使用正则表达式验证IP地址格式是否正确。
原文地址: https://www.cveoy.top/t/topic/pT1l 著作权归作者所有。请勿转载和采集!