2017-10-12 75 views
0

我想知道如何让文本框只接受小于或等于一个数字?C#文本框按键事件?

我有这个按键事件对我的文本框

//**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语句,用户只允许输入数字/整数和必须小于或等于号。当我运行程序时,是的,它不接受除数字以外的其他字符,但我可以输入大于总数。

+1

注意:你应该停下来一秒钟,并考虑如何用户实际上可以输入任何东西,如果代码的作品,你也想...(提示输入10一种类型1,0)。 –

+2

使用'NumericUpdown'控件。 –

+0

@RezaAghaei,要读取关于该控件的信息 –

回答

0

您的代码中有一些小错误(我为您修复),但最大的问题是,您没有检查之后的文本框的值 - 因此,用户可以输入超过允许的一个字符。它看起来像这样工作虽然:

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