Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Digit Grouping in .NET

How do we input digit grouping in C#? My code works but only for one instance. I have to constantly click it to group every number in the calculator. How do we do group it so that if we click it, it groups every number (not only the number presented), and if we uncheck the checkbox, it doesn't?

This is the current code:

NumberFormatInfo nFI = new CultureInfo("en-US", false).NumberFormat;


double int_value = Convert.ToDouble(textboxt1.text);


textbox1.Text = int_Value.ToString("N", nFI);
like image 644
14YearOldCuriousBoy Avatar asked Nov 05 '22 15:11

14YearOldCuriousBoy


1 Answers

Sounds like you're calling the formatting in the wrong place. You probably want to call that textbox1.Text = int_Value.ToString("N", nFI); when your value is changing in addition to when you click the checkbox (ie, whenever you click on your calculator buttons or on textboxt1.TextChanged or whatever), and only if your checkbox is checked (if (checkbox1.Checked == true) textbox1.Text...). It should also probably be in a separate function, that's called in all the places it's needed.

Edit for clarity

The problem you're likely having is that you have multiple sources that are changing the display in textbox1. The code you posted is most likely in some checkbox_CheckChanged(sender, e) event handler.

You likely also have code elsewhere (maybe calculator buttons or something) that will change the value in your textbox (something like...

double value = Convert.ToDouble(textbox.Text);
value = value + 1;
textbox1.Text = value.ToString();

in a +1 button, for example?)

What you want to do is have a separate displayValue(double value) function that will format it correctly all the time, maybe something like...

private void SetDisplayValue(double value)
{
    NumberFormatInfo nFI = new CultureInfo("en-US", false).NumberFormat
    if (checkBox.Checked == true)
        textbox1.Text = value.ToString("N", nFI);
    else
        textbox1.Text = value.ToString();
}

and every place that you would have set textbox1.Text in your code, regardless of whether it's in a button or a _CheckChanged or whatnot, instead call that private function.

like image 115
Tanzelax Avatar answered Nov 13 '22 17:11

Tanzelax