我有一個文本框,用戶應該在其中鍵入一個價格。 如果價格從0開始,則需要防止繼續鍵入。 例如,用戶無法鍵入「000」或「00009」。防止在輸入字符時繼續在文本框中鍵入
我在KeyPress上試過這個,但什麼都沒有!
if (txt.Text.StartsWith("0"))
return; Or e.Handeled = true;
我有一個文本框,用戶應該在其中鍵入一個價格。 如果價格從0開始,則需要防止繼續鍵入。 例如,用戶無法鍵入「000」或「00009」。防止在輸入字符時繼續在文本框中鍵入
我在KeyPress上試過這個,但什麼都沒有!
if (txt.Text.StartsWith("0"))
return; Or e.Handeled = true;
試試這個:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//only allow digit and (.) and backspace
if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
{
e.Handled = true;
}
var txt = sender as TextBox;
//only allow one dot
if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
{
e.Handled = true;
}
//if 0, only allow 0.xxxx
if (txt.Text.StartsWith("0")
&& !txt.Text.StartsWith("0.")
&& e.KeyChar != '\b'
&& e.KeyChar != (int)'.')
{
e.Handled = true;
}
}
的文本代替'e.KeyChar!='\ b'',最好使用'!char.IsControl(e.KeyChar)' – Nofuzy
您可以使用TextChanged
-event。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.textBox1.Text == "0") this.textBox1.Text = "";
}
這隻會在TextBox
在啓動時爲空時有效。
我不想清空開始時輸入0後的文本框。我只是想防止在這種情況下繼續打字。 – Nofuzy
您仍然可以使用改爲 –
我解決了它自己:
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
{
e.Handled = true;
return;
}
}
拒絕讓任何類型的價格開始時以0似乎是一個不好的用戶體驗 - 值得注意的是,他們可能要鍵入如果錯誤地輸入了該字符,則退格*刪除該字符。一種比較柔和的方法突出顯示文本框並拒絕提交整個表單,同時允許編輯/更正通常是首選。 –
是用戶可以退格並刪除,但如果以0開頭,則不能輸入其他字符。 – Nofuzy
應該是'e.Handeled = true'嗎? [參考](http://stackoverflow.com/a/2591284/1050927),您可能需要檢查用戶輸入'數字'而不是控制字符(退格,刪除...) – Prisoner