Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make textbox accept only currency format input?

Tags:

c#

validation

wpf

enter image description here

This is a screenshot of the program. As you see I made the output format how I wanted it to be. I used this code: <DataGridTextColumn Header="Price" Binding="{Binding Path=Price, StringFormat=C, ConverterCulture='de-DE'}"/>

How to make the textbox accept as input only numbers as currency format, or how to make it autoformat it while typing? I tried few codes that I found here and there but it didn't work. Hope someone can help me and give me some detailed information too. The data must be saved in SQL Server database, and till now I used LINQ.

like image 542
Tinaira Avatar asked Oct 26 '25 20:10

Tinaira


1 Answers

You can create a TextChanged event and format the text as you go.

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox1.Text = string.Format("{0:#,##0.00}", double.Parse(textBox1.Text));
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

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

Got this from: https://stackoverflow.com/a/15473340/5588364

And: https://stackoverflow.com/a/463335/5588364

like image 134
Edgar Mora Avatar answered Oct 28 '25 10:10

Edgar Mora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!