2016-04-13 42 views
0

我想要删除用户在文本框中按下的一个字符减去-。我验证该用户没有与事件key_press按下减号键两次:如何在字符串c中删除中间或末尾的字符( - )

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 < ---有效

我怎么能保证的减号开始文本框的内容?

+1

为什么不尝试将值转换为double值呢? – Wjdavis5

+0

你不应该只是警告用户输入无效吗?用户的意思是1000或-1000?你怎么能决定哪个是哪个? “如何能”==“承担责任,如果你猜错了” –

+0

嗨,我尝试转换为十进制但显示错误“格式异常”,当用户写一个数量1000-.00 –

回答

0

使用像这样

在类级别这样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("-",""); 
    } 
} 
+0

问题与InstanceOf ...这是在命名空间System.Object? –

+0

对不起,我想写的索引,而不是写instanceof它只是一个错字 – rashfmnb

+0

感谢的@rashfmnb在检查手表IndexOf(“ - ”)> 0, ,因为减号是第一个 –

0
if (e.KeyChar == '-' && ((sender as TextBox).Text.Length > 1)) 

这让一开始只有一个破折号。也许你需要先修剪文字......

+0

这不会工作,如果用户将键入一个数字,然后按[Home]按钮,然后尝试将该值设为负值。 – dasblinkenlight

+0

好的,你是对的 - 所以你的回答很好:-) – Markus

+0

我评论过,如果你想让它更一般化,你可以改变你的答案。 – dasblinkenlight

0

第二个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; 
} 
+0

但事件key_press不允许“return modifiedText.LastIndexOf(” - “)!= 0;”是无效的方法 –

+0

@RafaelSaavedra我打算把'e.Handled'设置为一个布尔结果。 – dasblinkenlight

+0

@RafaelSaavedra你给这个改变一个尝试吗? – dasblinkenlight