Converting text to decimal currency VS 2008 C#

I am trying to convert test to currency and I came across the code listed below. When I try to build my prject in VS 2008 C# this line has invalid arguments.

    if (!decimal.TryParse(this.txtTotalPrice.Text, NumberStyles.Currency))

This was taken out of a working VB program and converted to C#. What am I missing?
private void txtTotalPrice_Validating(object sender, CancelEventArgs e)
        {
            decimal currency = default(decimal);
    
            //Convert the current value to currency, with or without a currency symbol.
            
            if (!decimal.TryParse(this.txtTotalPrice.Text, NumberStyles.Currency)) {
            /*Don't let the user leave the field if the value is invalid. */
            {
                this.txtTotalPrice.HideSelection = false;
                this.txtTotalPrice.SelectAll();
            
                MessageBox.Show("Please enter a valid currency amount.", "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Error);

                this.txtTotalPrice.HideSelection = true;
            }
        
            e.Cancel = true;
        }
        }

Open in new window

rwheeler23Asked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi rwheeler23;

Remove all your Binding statements and leave the one I posted.

Fernando
// Just remove these Bindings from your code.

this.txtTotalQuantity.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalQTY").ToString();
this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalPrice").ToString();
this.txtTotalCost.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalCost").ToString();
this.txtAvgMargin.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "AvgMargin").ToString();

Open in new window

0
 
Alfred A.Commented:
Try this,

decimal.TryParse(this.txtTotalPrice.Text, out currency);
string str = currency.ToString("C2");
0
 
Alfred A.Commented:
Applying in your code snippet, something like:

decimal currency = default(decimal);
   
//Convert the current value to currency, with or without a currency symbol.

if (!decimal.TryParse(this.txtTotalPrice.Text, out currency)) {
            /*Don't let the user leave the field if the value is invalid. */
            {
                string str = currency.ToString("C2");
                this.txtTotalPrice.HideSelection = false;
                this.txtTotalPrice.SelectAll();
           
                MessageBox.Show("Please enter a valid currency amount.", "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Error);

                this.txtTotalPrice.HideSelection = true;
            }
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
Fernando SotoRetiredCommented:
Hi rwheeler23;

The two languages do not always translate the same way. The C# code below will work.

Fernando
using System.Globalization;

// Used to hold the converted string to Decimal
decimal theDecimalValue = 0;

// The null parameter in the following statement uses the current culture. 
if (!Decimal.TryParse(this.txtTotalPrice.Text, System.Globalization.NumberStyles.Currency, null, out theDecimalValue))
{
    // Invalid value could not convert
}

// The null parameter in the following statement uses the specific culture
if (!Decimal.TryParse(this.txtTotalPrice.Text, NumberStyles.Currency, CultureInfo.CreateSpecificCulture("en-GB"), out theDecimalValue))
{
    // Invalid value could not convert
}

Open in new window

0
 
samsymonCommented:
sorry.it was a wrong posting.
0
 
rwheeler23Author Commented:
FernandoSoto:

This solution works but please excuse my ignorance with my next question. The number I am formatting is a result of a SQL sum statement. My field name is txtTotalPrice. I want this format to occur so that when the field first appears on the screen w/o ever landing on it. Which event for this field should I insert this code so the field will appear formatting prior to landing and leaving the field?
0
 
Fernando SotoRetiredCommented:
Hi rwheeler23;

Not sure the question you are asking. You state, "The number I am formatting is a result of a SQL sum statement. My field name is txtTotalPrice. I want this format to occur so that when the field first appears on the screen w/o ever landing on it.", Well if the value is gotten from a database then set the text box just after the call is made. If the form you are putting this value does not exist yet then pass the value in the constructor and immediately set the text box value.

To your question, "Which event for this field should I insert this code so the field will appear formatting prior to landing and leaving the field?", Not understanding this. Let call the text box a control and the object coming from the database a field. Controls have events and fields do not. Please restate the question and also it will help to see the code you have to be able to answer the question correctly. When you say landing and leaving in the above statement do you mean the control getting and losing the focus?

Fernando
0
 
rwheeler23Author Commented:
I am new to VS 2008 C# so please excuse my use of the wrong terminology. I have included my code below. The portion of the code we are talking about is dealing with 4 text boxes. These text boxes contain the sum of the values that were previously displayed in a data grid above. Essentially what I am trying to do is to have the datadridview listing the detail and the text boxes to contain the totals of the columns in the datagridview. Formatting was simple in the dgv but I just cannot get these text boxes to format properly. This screen is 100% read-only so even though the user can land on a record they cannot modify anything. All I want is when the form is populated is to have these four text boxes to be formatted with the QTY field having no decimal places, the price and costs text boxes to be of the format $###,###.## and the margin field to be ##.##%
try
            {
                GPDataSet = new System.Data.DataSet();
                GPDataSet.CaseSensitive = false;

                GPCommand = new System.Data.SqlClient.SqlCommand();
                GPCommand.Connection = GPConnection;

                GPCommand.CommandText = "select sum(convert(int, sol.quantity)) AS 'TotalQTY',sum(sol.xtndprce) AS 'TotalPrice',sum(CASE WHEN pop.ponumber is NULL THEN sol.unitcost * sol.quantity ELSE pop.unitcost * sol.quantity END) as 'TotalCost',avg(CASE WHEN pop.unitcost* sol.quantity = 0 or pop.ponumber is NULL THEN CASE WHEN sol.extdcost = 0 THEN 0 ELSE (sol.xtndprce-sol.extdcost)/sol.extdcost * 100.00 END ELSE (sol.xtndprce-(pop.unitcost * sol.quantity))/(pop.unitcost * sol.quantity)  * 100.00 END) as 'AvgMargin' from sop10200 sol LEFT OUTER JOIN SOP60100 sop on sol.sopnumbe = sop.sopnumbe and sol.lnitmseq = sop.lnitmseq LEFT OUTER JOIN POP10110 pop on sop.ponumber = pop.ponumber and sop.ord = pop.ord WHERE SOL.SOPNUMBE = '" + sopEntryWindow.SopNumber.Value + "'"; 
                GPDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
            
                GPDataAdapter.SelectCommand = GPCommand;
                GPDataAdapter.TableMappings.Add("Table", "OrderSummary");

                GPDataAdapter.Fill(GPDataSet);

                this.txtTotalQuantity.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalQTY").ToString();
                this.txtTotalQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

                this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalPrice").ToString();
                this.txtTotalPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
                
                this.txtTotalCost.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalCost").ToString();
                this.txtTotalCost.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
                               
                this.txtAvgMargin.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "AvgMargin").ToString();
                this.txtAvgMargin.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
                
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
                        
        }

Open in new window

0
 
rwheeler23Author Commented:
I tried adding this but this does not work either.

this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalPrice").ToString();
                this.txtTotalPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

                decimal numericValue = Convert.ToDecimal(this.txtTotalPrice);
                txtTotalPrice.Text = numericValue.ToString("c");
0
 
Fernando SotoRetiredCommented:
Hi rwheeler23;

See code snippet to correct the formatting you want. Not the last parameter on each of the lines is the format string, C = Currency, D = Decimal, P = Percent. If you need to change them look at this documentation for other formats.

http://127.0.0.1:47873/help/1/ms.help?method=page&id=T%3ASYSTEM.GLOBALIZATION.NUMBERFORMATINFO&product=VS&productVersion=100&topicVersion=100&locale=EN-US

Documentation on the DataBindings.Add being used in the snippet.
http://127.0.0.1:47873/help/1/ms.help?method=page&id=M%3ASYSTEM.WINDOWS.FORMS.CONTROLBINDINGSCOLLECTION.ADD%28SYSTEM.STRING%2CSYSTEM.OBJECT%2CSYSTEM.STRING%2CSYSTEM.BOOLEAN%2CSYSTEM.WINDOWS.FORMS.DATASOURCEUPDATEMODE%2CSYSTEM.OBJECT%2CSYSTEM.STRING%2CSYSTEM.IFORMATPROVIDER%29&product=VS&productVersion=100&topicVersion=100&locale=EN-US

Fernando
this.txtTotalQuantity.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalQTY", true, DataSourceUpdateMode.Never, String.Empty, "D");

this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary", "TotalPrice"true, DataSourceUpdateMode.Never, String.Empty, "C");

this.txtTotalCost.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalCost", true, DataSourceUpdateMode.Never, String.Empty, "C");
               
this.txtAvgMargin.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "AvgMargin", true, DataSourceUpdateMode.Never, String.Empty, "P");

Open in new window

0
 
Fernando SotoRetiredCommented:
Also note that you do not need the ToString( ) method at the end of the call.
0
 
rwheeler23Author Commented:
I will give this a try tomorrow. I was not sure if I could do anything with those bound data controls.
0
 
rwheeler23Author Commented:
Please revise your links. The ones you listed are pointed locally.
0
 
Fernando SotoRetiredCommented:
0
 
rwheeler23Author Commented:
When I adjusted my code as per your suggestions the values changed:

TotalQTY  was 40 is now 40.00000
TotalPrice was $2,887.50 is now BLANK
TotalCost was $2,116.37 is now BLANK
AvgMargin was 37.60% is now BLANK
I will start reading your links to see where they lead me.
 GPDataSet = new System.Data.DataSet();
                GPDataSet.CaseSensitive = false;

                GPCommand = new System.Data.SqlClient.SqlCommand();
                GPCommand.Connection = GPConnection;

                GPCommand.CommandText = "select sum(sol.quantity) AS 'TotalQTY',sum(sol.xtndprce) AS 'TotalPrice',"+
                "sum(CASE WHEN pop.ponumber is NULL THEN sol.unitcost * sol.quantity ELSE pop.unitcost * sol.quantity END) as 'TotalCost',"+
                "avg(CASE WHEN pop.unitcost* sol.quantity = 0 or pop.ponumber is NULL THEN CASE WHEN sol.extdcost = 0 THEN 0 ELSE "+
                "(sol.xtndprce-sol.extdcost)/sol.extdcost * 100.00 END ELSE (sol.xtndprce-(pop.unitcost * sol.quantity))/(pop.unitcost * sol.quantity)  * 100.00 END) as "+
                "'AvgMargin' from sop10200 sol LEFT OUTER JOIN SOP60100 sop on sol.sopnumbe = sop.sopnumbe and sol.lnitmseq = sop.lnitmseq LEFT OUTER JOIN POP10110 pop "+
                "on sop.ponumber = pop.ponumber and sop.ord = pop.ord WHERE SOL.SOPNUMBE= '" + sopEntryWindow.SopNumber.Value + "'";

                GPDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
            
                GPDataAdapter.SelectCommand = GPCommand;
                GPDataAdapter.TableMappings.Add("Table", "OrderSummary");

                GPDataAdapter.Fill(GPDataSet);

                this.txtTotalQuantity.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalQTY").ToString();
                this.txtTotalQuantity.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalQTY", true, DataSourceUpdateMode.Never, string.Empty, "D");
                this.txtTotalQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
                
                this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalPrice").ToString();
                this.txtTotalPrice.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalPrice", true, DataSourceUpdateMode.Never, string.Empty, "C");
                this.txtTotalPrice.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

                this.txtTotalCost.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalCost").ToString();
                this.txtTotalCost.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "TotalCost", true, DataSourceUpdateMode.Never, string.Empty, "C");
                this.txtTotalCost.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

                this.txtAvgMargin.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "AvgMargin").ToString();
                this.txtAvgMargin.DataBindings.Add("Text", GPDataSet.Tables["OrderSummary"], "AvgMargin", true, DataSourceUpdateMode.Never, string.Empty, "P");
                this.txtAvgMargin.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

Open in new window

0
 
rwheeler23Author Commented:
I see what you mean. I will be getting back to this code on Tuesday and will make this adjustment.
0
 
rwheeler23Author Commented:
This was perfect. Thanks for your help.
0
 
Fernando SotoRetiredCommented:
Not a problem, always glad to help.  ;=)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.