ITPUB论坛 » Web开发 » ASP.NET与AJAX » 限制TextBox输入暂定内容
新一届的微软MVP评选已经开始,欢迎各位推荐!
2008-7-3 19:30 dotnetworker
限制TextBox输入暂定内容

1、如何限制TextBox只能输入0-255之间的数字,要求向Windows一样一输入错误马上就能给出提示
2、如何判断在TextBox中输入的子网掩码格式是否正确(即转换为二进制后,前几位全为1,后几位全为0)

2008-7-3 19:32 juanpeng
TextBox的TextChange事件里
判断
int txt;
try
{
txt = Convert.ToInt(TextBox.Text);
}
catch
{
//输入的不是数字
}

if(txt < 0 ¦ ¦ txt >255)
//只能输入0-255之间的数字

2008-7-3 19:32 smartpig
用验证控件

2008-7-3 19:33 juan002
做一个判断函数,用来检查是不是符合要求的

看看MSDN上的类似代码吧:

下面的代码示例使用 KeyPress 事件来禁止向控件输入字符。
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 ¦ ¦ e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 ¦ ¦ e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}

2008-7-18 09:58 382564549
用ajax验证控件

2008-7-18 22:14 X二
1、RichTextBox可以设置正则表达式
2、有验证控件可以做出错误提示

页: [1]


Powered by ITPUB论坛