0

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. 但是我再次编辑此文本框值并按回车键,它给出了一个错误:“输入字符串格式不正确”指向下面的行:

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

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

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

多谢你们。

4

1 回答 1

2

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

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));

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

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 Enter Event 上,您可以执行以下操作:

void TextBox_EnterEvent(object sender, EventArgs e)
{
    var tb = sender as TextBox;
    tb.Text = RemoveCurrencyFormating(tb.Text);
}
于 2013-05-04T13:36:05.183 回答