简体   繁体   中英

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. 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. 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**
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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