3

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.

Tinaira
  • 727
  • 2
  • 7
  • 23

2 Answers2

8

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

Community
  • 1
  • 1
Edgar Mora
  • 104
  • 5
  • instead of double.Parse I made decimal.Parse. but there is a problem. when I try to write the 2 digits after the point, for the cents, I get a performance issue, i have to manually point there with the cursor and type the 2 digits in 1 second/// the second event don't apply in wpf, if you know how to manipulate it to work with wpf would be awesome – Tinaira Nov 21 '15 at 22:53
  • 2
    Using the code provided, when I type the numbers are reversed in order as a type. basically if I type 34, it would show up as 43. what is causing this? – goodfella Jun 25 '16 at 02:27
  • So trivial stuff did so much problems and headaches.. MaskedTextBox is really useless control. Thanks for this solution, works like a charm! – Artiom Apr 27 '17 at 07:21
  • @goodfella That's because of the design of this answer. Check my answer here for validating currency as the user types. https://stackoverflow.com/a/65964280/591285 – clamchoda Jan 30 '21 at 03:16
1

you can simply prevent adding non-numerical chars by this simple code

 if (long.TryParse(TextBox.Text,out long isparsable))
        {
          // your code to handle numbers
        }
        else
        {
            TextBox.Text="Only Numbers Allowed";
            TextBox.Focus();
            TextBox.SelectAll();
        }
Mohsen K
  • 257
  • 4
  • 10