我需要在C#中限制我的TextBox中允许的位数。
我还需要创建验证,以便它将类似于一个手机号码,这意味着它必须从07开始,总共有11位数字。
有什么建议吗?
发布于 2012-11-30 04:51:51
您可以使用MaskedTextBox来提供受控制的输入值。后跟11位掩码的"07“将是\0\700000000000。
发布于 2015-12-24 17:11:29
你没有任何代码作为例子,所以,我会输入我的代码。
要限制字符数,应键入以下代码:
private bool Validation()
{
if (textBox.Text.Length != 11)
{
MessageBox.Show("Text in textBox must have 11 characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}如果您希望textBox中文本以"07“开头,则应键入以下代码:
private bool Validation()
{
string s = textBox.Text;
string s1 = s.Substring(0, 1); // First number in brackets is from wich position you want to cut string, the second number is how many characters you want to cut
string s2 = s.Substring(1, 1);
if (s1 != "0" || s2 != "7")
{
MessageBox.Show("Number must begin with 07", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}您可以将其合并到ofcource的一个方法中,并且您可以在任何时候调用它。如果您想调用某些方法(例如,当您单击accept按钮时),只需键入以下代码:
private void buttonAccept_Click(object sender, EventArgs e)
{
if (Validation() == false) return;
}https://stackoverflow.com/questions/13633497
复制相似问题