[英]How remove characters minus (-) in middle or end in string c#
我要刪除一個字符減-
用戶在文本框中按下。 我確認用戶沒有通過事件key_press
兩次按下減號鍵:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1))
{
e.Handled = true;
}
問題是當用戶按下字符串中間或結尾的減號鍵時。 例如:
1000.-00 <---無效
2000.00- <---無效
-1000.00 <---有效
如何確保減號是文本框內容的開頭?
這樣使用
在類級別聲明一個變量,例如int minusCount = 0;
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
//put condition if it is zero than only allow one minus sign
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1) && minusCount==0)
{
e.Handled = true;
//over here increment that variable
minusCount = minusCount+1;
//for handling it in middle other than zero position
if(textbox.Text.IndexOf("-")>1)
{
textbox.Text=textbox.Text.Replace("-","");
}
}
if (e.KeyChar == '-' && ((sender as TextBox).Text.Length > 1))
開始時只允許一個破折號。 也許您需要先修剪文本...
第二個if
的問題是,在您檢查sender
(即TextBox
)時還沒有減號。 您應該首先用減號構造文本,然后驗證它以做出決定:
if (e.KeyChar == '-') {
var tb = sender as TextBox;
// Obtain the text after the modification
var modifiedText = tb.Text.Insert(tb.SelectionStart, "-");
// There will be at least one '-' in the text box - the one you just inserted.
// Its position must be 0, otherwise the string is invalid:
e.Handled = modifiedText.LastIndexOf("-") != 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.