2017-10-12 72 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** 
    } 
}