How to make textbox accept only currency format input?

12,200

Solution 1

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

Solution 2

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();
        }
Share:
12,200
Tinaira
Author by

Tinaira

Updated on June 07, 2022

Comments

  • Tinaira
    Tinaira almost 2 years

    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.