繁体   English   中英

Windows Forms C# - 动态掩码文本框钱输入

[英]Windows Forms C# - Dynamic mask textbox money Input

Windows Forms C# - 我想创建一个文本框,每当用户从文本框中键入或删除一个键时,该文本框就会自动更改。 我开发了部分代码。

    //This will convert value from textbox to currency format when focus leave textbox
    private void txtValormetrocubico_Leave(object sender, EventArgs e)
    {
        decimal cubic = Convert.ToDecimal(txtValormetrocubico.Text);
        txtValormetrocubico.Text = string.Format("{0:c}", Convert.ToDecimal(cubic));
        MessageBox.Show(txtValormetrocubico.Text);
    }


    //this only allow numbers and "." and "," on textimbox imput
    private void txtValormetrocubico_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar)
    && !char.IsDigit(e.KeyChar)
    && e.KeyChar != '.' && e.KeyChar != ',')
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.'
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }

            if (e.KeyChar == ','
                && (sender as TextBox).Text.IndexOf(',') > -1)
            {
                e.Handled = true;
            }          
    }

我第一次在文本框中输入值时,该值将完美地转换为货币格式,例如300$ 300.00 但我再次编辑此文本框值并按Enter键,它给出一个错误:“输入字符串不是正确的格式”指向下面的行:

decimal cubic = Convert.ToDecimal(txtValormetrocubico.Text);

我认为问题是由于该值已经是十进制格式的事实。 因此,当我单击该字段并再次按Enter键时,会导致错误,因为无法解析该值。 如何避免此错误?

编辑:我之前的问题是我的第一个问题。 由于我是新用户并且对C#知之甚少,我忘了发布我的代码。 在研究了一些之后,我做了部分工作。 只剩下这个小问题。 请投票,我被禁止,不能提出新的问题因为我有7票。

多谢你们。

问题是该字符串包含货币符号

private void TextBox_LeaveEvent(object sender, EventArgs e)
{
    var tb = sender as TextBox;
    if(tb.Text.Length>0){
        decimal cubic = Convert.ToDecimal(tb.Text);
        tb.Text = string.Format("{0:c}", Convert.ToDecimal(cubic));
        label1.Text = tb.Text;
    }
}

textbox.Text上方设置为包含货币信息:

tb.Text = string.Format("{0:c}", Convert.ToDecimal(cubic));

由于文本框现在包含货币符号(如€或$),因此只要TextBox_LeaveEvent再次触发, Convert.ToDecimal就会失败:

decimal cubic = Convert.ToDecimal(tb.Text);

如果你想要使用c#蒙面文本框,你可以找到有关蒙版文本框的文章 你冷也测试字符串是否包含任何非数字字符串( if(tbText.IndexOf(" ") >-1){...}

更新基本示例

我上传了一个非常基本的例子来删除格式化为github 的货币

string RemoveCurrencyFormating(string input)
{    
    if(input.IndexOf(" ") !=-1){
       var money = input.Substring(0, input.IndexOf(" ")-1);            
       return String.Format("{0:D0}", money);               
    }
    return ""; // Todo: add Error Handling
}

在TextBox上输入事件,您可以执行以下操作:

void TextBox_EnterEvent(object sender, EventArgs e)
{
    var tb = sender as TextBox;
    tb.Text = RemoveCurrencyFormating(tb.Text);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM