Skip to main content
 首页 » 编程设计

c#之由于制表符而突出显示时想要覆盖文本框上的值

2024年02月23日18mayingbao

我有一个只接受这些值的文本框:

. , - $ m M k K b B 和数字

它也只接受最多两位小数。我的问题是,在我关闭文本框然后再次选择它之后,我无法输入任何信息或覆盖文本框中已有的任何内容。

/// Checks if the decimal places are more than 2 and it will not allow user to keyin if its more than 2. 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
private void txtAmount_KeyDown(object sender, KeyEventArgs e) 
{ 
    string textValue = txtAmount.Text.Trim(); 
    if (textValue.IndexOf(".") > 0) 
    { 
        string[] decimalvalue = textValue.Split(new char[] { '.' }); 
        if (decimalvalue[1].Length >= 2) 
            cancelCharacter = true; 
        else 
            cancelCharacter = false; 
    } 
} 
 
/// <summary> 
/// Doesn't allow the user to enter any other value other than  
/// ". , - $ m M k K b B and numbers" 
/// </summary> 
/// <param name="sender"></param> 
/// <param name="e"></param> 
private void txtAmount_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if ((e.KeyChar < 48 || e.KeyChar > 57) && 
         e.KeyChar != 46 && e.KeyChar != 36 && e.KeyChar != 36 && e.KeyChar != 32 && e.KeyChar != 44 && e.KeyChar != 8 && e.KeyChar != 45 && 
         e.KeyChar != 75 && e.KeyChar != 107 && e.KeyChar != 77 && e.KeyChar != 109 && e.KeyChar != 66 && e.KeyChar != 98) 
    { 
        e.Handled = true; 
    } 
    else if (cancelCharacter && e.KeyChar != 8 && e.KeyChar != 45 && 
             e.KeyChar != 75 && e.KeyChar != 107 && e.KeyChar != 77 && e.KeyChar != 109 && e.KeyChar != 66 && e.KeyChar != 98) 
    { 
        e.Handled = true; 
    } 
    else if (e.KeyChar == '.' && txtAmount.Text.IndexOf(".") > -1 || cancelCharacter && e.KeyChar != 8) 
    { 
        e.Handled = true; 
    } 
} 

请您参考如下方法:

看起来您需要重置您的 cancelCharacter 标志。处理 Leave 事件:

private void txtAmount_Leave(object sender, EventArgs e) 
{ 
    cancelCharacter = false; 
} 

这个怎么样。更改您的 keydown 事件中的这一行以查看选择了多少个字符:

if (decimalvalue[1].Length >= 2 && txtAmount.SelectionLength < 1 &&  
    txtAmount.SelectionStart > textValue.IndexOf("."))