Decimal Formatting VS 2008 C#

I am new to VS C# and I am trying to find the proper way to format decimal fields. I first placed text fields on the WinForm and then discovered MaskedTextBoxes. What I cannot figure out is how to format the fields as you are typing. I would like the dollar sign ($) to stay in front of the numbers and if you type 25.2 to have it convert to $25.20 when leaving the field. I want my maximum number to be $99,999,999.99 and the user to be able to type in any size number up to that maximum and have it converted to the corresponding number with two decimal places. There does not appear to be a mask to do this so I am thinking some code is necessary. I just need to number to be converted when the user leaves the field. What is the proper way to accomplish this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Dexterity.Bridge;
using Microsoft.Dexterity.Applications;
using Microsoft.Dexterity.Shell;
using Microsoft.Dexterity.Applications.DynamicsDictionary;

namespace PPActivityDetail
{
    public partial class frmPPBreakdown : DexUIForm
    {
        // Create a reference to the Cash Receipts Entry window
        static RmCashReceiptsForm CashReceiptsForm = Dynamics.Forms.RmCashReceipts;
        static RmCashReceiptsForm.RmCashReceiptsWindow RmCashReceiptsWindow = CashReceiptsForm.RmCashReceipts;

        // Define connection string
        string ConnectionString = "";

        // Setup SQL Connection Handlers
        private System.Data.SqlClient.SqlConnection DataConnection; 
        private System.Data.DataSet DataDataSet;
        private System.Data.SqlClient.SqlCommand DataCommand;
        private System.Data.SqlClient.SqlDataAdapter DataDataAdapter;

        /* Define variable to hold record exists flag */
        Boolean RecordExists = false;
        int RecordCount;
        
        // Define variables to hold batch number and batch source
        string BatchSource;
        string BatchNumber;

        public frmPPBreakdown()
        {
            InitializeComponent();

            /* Assign values to text box fields */
            txtBatchNumber.Text = RmCashReceiptsWindow.BatchNumber;
            txtDocumentNumber.Text = RmCashReceiptsWindow.DocumentNumber;
            txtCustomerNumber.Text = RmCashReceiptsWindow.CustomerNumber;
            txtDocumentDate.Text = RmCashReceiptsWindow.DocumentDate.Value.ToString("MM/dd/yy");

            /* Assign value for Batch Source and Batch Name */
            BatchSource = RmCashReceiptsWindow.BatchSource;
            BatchNumber = RmCashReceiptsWindow.BatchNumber;

            try
            {
                SqlConnection DataConnection = GetConnection();

                DataDataSet = new System.Data.DataSet();
                DataDataSet.CaseSensitive = false;

                DataCommand = new System.Data.SqlClient.SqlCommand();
                DataCommand.Connection = DataConnection;

                DataCommand.CommandText = "SELECT GLPOSTDT FROM SY00500 WHERE BCHSOURC = '" + BatchSource + "' AND BACHNUMB = '" + BatchNumber + "'";

                DataDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
                DataDataAdapter.SelectCommand = DataCommand;
                DataDataAdapter.TableMappings.Add("Table", "POSTINGDATE");

                DataDataAdapter.Fill(DataDataSet);

                txtPostDate.Text = DataDataSet.Tables["POSTINGDATE"].Rows[0]["GLPOSTDT"].ToString();

                if (txtPostDate.Text != "")
                {
                    txtPostDate.Text = Convert.ToDateTime(txtPostDate.Text).ToString("MM/dd/yy");
                }

                DataCommand.CommandText = "SELECT COUNT(*) as RECORDCOUNT FROM rbsPPACTIVITY WHERE DOCNUMBR = '" + RmCashReceiptsWindow.DocumentNumber + "'";
                DataDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
                DataDataAdapter.SelectCommand = DataCommand;
                DataDataAdapter.TableMappings.Add("Table", "RECORDCOUNT");

                DataDataAdapter.Fill(DataDataSet);
                RecordCount = Convert.ToInt16(DataDataSet.Tables["RECORDCOUNT"].Rows[0]["RECORDCOUNT"].ToString());

                if (RecordCount > 0)
                {

                    DataCommand.CommandText = "SELECT JOBNUMBR,INVCNMBR,RCPTRCVD,RCPTDISC,PPREQSTD,PPPAID,PPRECOUP,SALSALES,SALFRGHT,SALGRPAID FROM rbsPPACTIVITY WHERE DOCNUMBR = '" + RmCashReceiptsWindow.DocumentNumber + "'";

                    DataDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
                    DataDataAdapter.SelectCommand = DataCommand;
                    DataDataAdapter.TableMappings.Add("Table", "JOBDATA");

                    DataDataAdapter.Fill(DataDataSet);
                    
                    txtJobNumber.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["JOBNUMBR"].ToString();
                    txtInvoiceNumber.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["INVCNMBR"].ToString();
                    txtReceiptsReceived.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["RCPTRCVD"].ToString();
                    txtReceiptsDiscounts.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["RCPTDISC"].ToString();
                    txtPPRequested.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["PPREQSTD"].ToString();
                    txtPPPaid.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["PPPAID"].ToString();
                    txtPPRecoup.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["PPRECOUP"].ToString();
                    txtSales.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["SALSALES"].ToString();
                    txtSalFreight.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["SALFRGHT"].ToString();
                    txtSalGRPaid.Text = DataDataSet.Tables["JOBDATA"].Rows[0]["SALGRPAID"].ToString();
                    /*
                    txtReceiptsReceived.Text = Convert.ToDecimal(txtReceiptsReceived.Text).ToString("C");
                    txtReceiptsDiscounts.Text = Convert.ToDecimal(txtReceiptsDiscounts.Text).ToString("C");
                    txtPPRequested.Text = Convert.ToDecimal(txtPPRequested.Text).ToString("C");
                    txtPPPaid.Text = Convert.ToDecimal(txtPPPaid.Text).ToString("C");
                    txtPPRecoup.Text = Convert.ToDecimal(txtPPRecoup.Text).ToString("C");
                    txtSales.Text = Convert.ToDecimal(txtSales.Text).ToString("C");
                    txtSalFreight.Text = Convert.ToDecimal(txtSalFreight.Text).ToString("C");
                    txtSalGRPaid.Text = Convert.ToDecimal(txtSalGRPaid.Text).ToString("C"); */

                    RecordExists = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message);
            }
          
        }

        private SqlConnection GetConnection()
        {
            // Create reader and open file containing connection string
            TextReader tr = new StreamReader(@"C:\Program Files\Microsoft Dynamics\GP\Addins\GSE.INI");

            // Read line containing the connection string
            ConnectionString = tr.ReadLine();

            // Close the stream
            tr.Close();
          
            DataConnection = new System.Data.SqlClient.SqlConnection(ConnectionString);
            DataConnection.Open();

            return DataConnection;
        }

        private void frmPPBreakdown_Load(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con = GetConnection();
                SqlCommand cmd = new SqlCommand();

                cmd.CommandType = CommandType.StoredProcedure;

                if (txtReceiptsReceived.Text.StartsWith("$"))
                {
                    txtReceiptsReceived.Text = txtReceiptsReceived.Text.Substring(1,txtReceiptsReceived.Text.Length-1);
                }
                if (txtReceiptsDiscounts.Text.StartsWith("$"))
                {
                    txtReceiptsDiscounts.Text = txtReceiptsDiscounts.Text.Substring(1, txtReceiptsDiscounts.Text.Length - 1);
                }
                if (txtPPRequested.Text.StartsWith("$"))
                {
                    txtPPRequested.Text = txtPPRequested.Text.Substring(1, txtPPRequested.Text.Length - 1);
                }
                if (txtPPPaid.Text.StartsWith("$"))
                {
                    txtPPPaid.Text = txtPPPaid.Text.Substring(1, txtPPPaid.Text.Length - 1);
                }
                if (txtPPRecoup.Text.StartsWith("$"))
                {
                    txtPPRecoup.Text = txtPPRecoup.Text.Substring(1, txtPPRecoup.Text.Length - 1);
                }
                if (txtSales.Text.StartsWith("$"))
                {
                    txtSales.Text = txtSales.Text.Substring(1, txtSales.Text.Length - 1);
                }
                if (txtSalFreight.Text.StartsWith("$"))
                {
                    txtSalFreight.Text = txtSalFreight.Text.Substring(1, txtSalFreight.Text.Length - 1);
                }
                if (txtSalGRPaid.Text.StartsWith("$"))
                {
                    txtSalGRPaid.Text = txtSalGRPaid.Text.Substring(1, txtSalGRPaid.Text.Length - 1);
                }

                cmd.Parameters.Add(new SqlParameter("@BACHNUMB", txtBatchNumber.Text));
                cmd.Parameters.Add(new SqlParameter("@DOCNUMBR", txtDocumentNumber.Text));
                cmd.Parameters.Add(new SqlParameter("@CUSTNMBR", txtCustomerNumber.Text));
                cmd.Parameters.Add(new SqlParameter("@DOCDATE", Convert.ToDateTime(txtDocumentDate.Text).ToString("MM/dd/yy")));
                cmd.Parameters.Add(new SqlParameter("@POSTDATE", Convert.ToDateTime(txtPostDate.Text).ToString("MM/dd/yy")));
                cmd.Parameters.Add(new SqlParameter("@JOBNUMBR", txtJobNumber.Text));
                cmd.Parameters.Add(new SqlParameter("@INVCNMBR", txtInvoiceNumber.Text));
                cmd.Parameters.Add(new SqlParameter("@RCPTRCVD", Convert.ToDecimal(txtReceiptsReceived.Text)));
                cmd.Parameters.Add(new SqlParameter("@RCPTDISC", Convert.ToDecimal(txtReceiptsDiscounts.Text)));
                cmd.Parameters.Add(new SqlParameter("@PPREQSTD", Convert.ToDecimal(txtPPRequested.Text)));
                cmd.Parameters.Add(new SqlParameter("@PPPAID", Convert.ToDecimal(txtPPPaid.Text)));
                cmd.Parameters.Add(new SqlParameter("@PPRECOUP", Convert.ToDecimal(txtPPRecoup.Text)));
                cmd.Parameters.Add(new SqlParameter("@SALSALES", Convert.ToDecimal(txtSales.Text)));
                cmd.Parameters.Add(new SqlParameter("@SALFRGHT", Convert.ToDecimal(txtSalFreight.Text)));
                cmd.Parameters.Add(new SqlParameter("@SALGRPAID", Convert.ToDecimal(txtSalGRPaid.Text)));
               
                if (RecordExists)
                {
                    cmd.CommandText = "rbsUPDATE_PPACTIVITY";
                }
                else
                {
                    cmd.CommandText = "rbsINSERT_PPACTIVITY";
                }

                cmd.Connection = con;

                cmd.ExecuteNonQuery();

                con.Close();

                this.Hide();
                this.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR::" + ex.Message);
                this.Close();

            }
        }
    }
}

Open in new window

Decimal.jpg
rwheeler23Asked:
Who is Participating?
 
käµfm³d 👽Commented:
I think the easiest way would be to handle the Leave event of the TextBox/MaskedTextBox and format the string in that handler:
private void maskedTextBox1_Leave(object sender, EventArgs e)
{
    double value;

    if (this.maskedTextBox1.Text.Length > 0 && double.TryParse(this.maskedTextBox1.Text, out value))
    {
        this.maskedTextBox1.Text = string.Format("{0:C}", value);
    }
}

Open in new window

0
 
rwheeler23Author Commented:
I found some code and pasted parts of it together. Now the question is how do invoke this code so that is does the formtting of the decimal numbers? What I am trying to accomplish is this.

Let say the final number will be $1,234.56. When the screen appears the number starts off as
$0.00

You type
1- $0.01
2-$0.12
3-$1.23
4-$12.34
5-$123.45
6-$1234.56

I am not sure if the code I have is correct and I definitely know I am not invoking it properly.
======================================================================
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Dexterity.Bridge;
using Microsoft.Dexterity.Applications;
using Microsoft.Dexterity.Shell;

namespace TestMaskedTextBox
{
    public partial class frmTestText : DexUIForm
    {
        public frmTestText()
        {
            InitializeComponent();
        }

        private void txtTestText_KeyPress(object sender, KeyPressEventArgs e)
        {
           
            txtTestText.Text = MaskedTextBox(txtTestText);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms.TextBox;

namespace MaskedTextBox
{
	public enum Mask {None, DateOnly, PhoneWithArea, IpAddress, SSN, Decimal, Digit };
	private Mask m_mask;

    public Mask Maked
	{
		get { return m_mask;}
		set {
			m_mask = value;
			this.Text="";
	}
		
	this.KeyPress += new  KeyPressEventHandler(this.OnKeyPress);                          

    private void OnKeyPress(object sender, KeyPressEventArgs e)
    {                                                          
		MaskedTextBox sd = (MaskedTextBox) sender;           
            if (sd.m_IPAddrOnly)                                 
                  sd.MaskIpAddr(e);                              
            if (sd.m_digitOnly)                                  
                  sd.MaskDigit(e);                               
            if(sd.m_ssn)                                         
                  sd.MaskPhoneSSN(e, 3, 2);                      
            if(sd.m_phoneOnly)                                   
                  sd.MaskPhoneSSN(e, 3, 3);                      
            if(sd.m_dateOnly)                                    
                  sd.MaskDate(e);                                
            if(sd.m_decimalOnly)                                 
                  sd.MaskDecimal(e);                             
    }    
    
    private void OnLeave(object sender, EventArgs e)            
	{                                                           
		MaskedTextBox sd = (MaskedTextBox) sender;            
		Regex regStr;                                         
		switch(m_mask)                                        
		{                                                     
			case Mask.DateOnly:                             
				regStr = new Regex(@"\d{2}/\d{2}/\d{4}"); 
				if(!regStr.IsMatch(sd.Text))              
					errorProvider1.SetError(this, "*"); 
				break;                                    

			case Mask.PhoneWithArea:                        
				regStr = new Regex(@"\d{3}-\d{3}-\d{4}"); 
				if(!regStr.IsMatch(sd.Text))              
					errorProvider1.SetError(this,"**"); 
				break;                                    

			case Mask.IpAddress:                            
				short cnt=0;                              
				int len = sd.Text.Length;                 
				for(short i=0; i<len;i++)                 
					if(sd.Text[i] == '.')               
					{                                   
						cnt++;                        
						if(i+1 < len)                 
							if(sd.Text[i+1] == '.') 
							{                       
								errorProvider1.SetError(this, "*"); 
								break;            
							}                       
					}                                   
                    if(cnt < 3 || sd.Text[len-1] == '.')      
                        errorProvider1.SetError(this, "*"); 
                    break;        
                                                
			case Mask.SSN:                                  
				regStr = new Regex(@"\d{3}-\d{2}-\d{4}"); 
				if(!regStr.IsMatch(sd.Text))              
					errorProvider1.SetError(this, "*"); 
				break;     
                                           
			case Mask.Decimal:                              
				break;                                    

			case Mask.Digit:                                
				break;                                    
		}                                                     
		  
	}
}

Open in new window

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.