我想知道如何让文本框只接受小于或等于数字?
我的文本框有这个按键事件
//**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**
}
}
对于我的IF语句,用户只能输入数字/整数,且必须小于或等于数字。当我运行该程序时,是的它不接受除数字之外的其他字符,但我可以输入大于总数。
答案 0 :(得分:0)
您的代码中有一些小错误(我为您修复了),但最大的问题是,在输入数字之后没有检查textBox 的值但是之前 - 因此用户可以输入超过允许的一个字符。它看起来像那样:
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**
}
}