简体   繁体   English

C#文本框按键事件?

[英]C# Textbox Keypress Event?

I was wondering how can I make the textbox only accepts less than or equal to a number? 我想知道如何使文本框只接受小于或等于数字的值?

I have this keypress event for my textbox 我的文本框有此按键事件

//**This will select and count the number of rows for a certain topic**

OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = @"SELECT COUNT(CONTENT) FROM qPIPE WHERE CONTENT = '" + topic + "'";
OleDbDataAdapter dAdap = new OleDbDataAdapter(command);
DataTable dTable = new DataTable();
dAdap.Fill(dTable);

private void txtNo_KeyPress(object sender, KeyPressEventArgs e)
{
    topic = cmbTopic.Text;

    //**This is to get the cell value of the DataTable**
    int total = Int32.Parse(dTable.Rows[0][0].ToString());

    //**Int32.Parse(txtNo.Text) >= total, convert the txtNo.Text to integer and compare it to total (total number of rows), ideally**
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && Int32.Parse(txtNo.Text) >= total

    {
        System.Media.SystemSounds.Beep.Play(); //**Plays a beep sound to alert an error**
        e.Handled = true; //**Prevent the character from being entered**
    }
}

For my IF statement, the user is only allowed to input a numeric/integer and must be less than or equal to a number. 对于我的IF语句,只允许用户输入数字/整数,并且必须小于或等于数字。 And when I run the program, yes it doesn't accept other characters except a number, but I can input greater than the total number. 是的,当我运行该程序时,是的,它不接受除数字以外的其他字符,但是我可以输入大于总数的数字。

You had a few minor mistakes in your code (which I fixed for you), the biggest problem however was, that you didn't check the value of the textBox after you entered the number but before - hence the user could enter one character more than allowed. 您在代码中犯了一些小错误(我为您解决了),但是最大的问题是,您输入数字之后但之前没有检查textBox的值-因此用户可以再输入一个字符超出允许范围。 It seems to work like that though: 它似乎像这样工作:

private void txtNo_KeyPress (object sender, KeyPressEventArgs e)
{
    topic = cmbTopic.Text;

    //**This is to get the cell value of the DataTable**
    int total = Int32.Parse (dTable.Rows [0] [0].ToString ());

    //**Int32.Parse(txtNo.Text) >= total, convert the txtNo.Text to integer and compare it to total (total number of rows), ideally**
    if (!char.IsControl (e.KeyChar) && !char.IsDigit (e.KeyChar) || char.IsDigit(e.KeyChar) && txtNo.Text.Length > 0 && Int32.Parse (txtNo.Text + e.KeyChar) > total)

    {
        System.Media.SystemSounds.Beep.Play (); //**Plays a beep sound to alert an error**
        e.Handled = true; //**Prevent the character from being entered**
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM