hi there,

i have a mask textbox in C# which saves $9999999999.99 as the mask, i have a database field should take the value and save it. the database feield is in money .but when i am writing the C# method to insert it into the data i convert the string into double and then i am trying to insert it into a money database field.

but when the mask text box value is empty it gives an error FormatException saying that the input string was not formatted correctly
tha code is below the error comes from the place where i have bolede the code

public void AddTopicDetails(int phase, String title, String topicNo, String subTitle, String agency, String type, String status,
            String sessionName,String Amt, DateTime startDate, DateTime endDate, String doNotProceed, String reason, String Option, String OAmt, DateTime Osdate, DateTime Oedate)
        {
            try
            {
                db.openConnection();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Datebase open connection Failed");
            }
            finally
            {
                String query = @"Insert into Topic (Phase,TTitle,TopicNo,SubTitle,Agency,Type,Status,TSessionName,TAmount,TSDate,TEDate,DoNotProceed,Reason,TOption,TOptionAmt,TOptionSDate,TOptionEDate) 
                        Values (@phase,@title,@topicNo,@subTitle,@agency,@type,@status,@sessionName,@tamt,@sDate,@eDate,@doNotProceed,@reason,@option,@oamt,@osdate,@oedate)";

                SqlCommand command = new SqlCommand(query,DB.getConnection());
                
                command.Parameters.Add("@phase", SqlDbType.VarChar).Value = phase;
                command.Parameters.Add("@title", SqlDbType.VarChar).Value = title;
                command.Parameters.Add("@topicNo", SqlDbType.VarChar).Value = topicNo;
                command.Parameters.Add("@subTitle", SqlDbType.VarChar).Value = subTitle;
                command.Parameters.Add("@agency", SqlDbType.VarChar).Value = agency;
                command.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
                command.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
                command.Parameters.Add("@sessionName", SqlDbType.VarChar).Value = sessionName;
                [B]command.Parameters.Add("@tamt", SqlDbType.Money).Value = Double.Parse(Amt);[/B]
                command.Parameters.Add("@sDate", SqlDbType.DateTime).Value = startDate;
                command.Parameters.Add("@eDate", SqlDbType.DateTime).Value = endDate;
                command.Parameters.Add("@doNotProceed", SqlDbType.VarChar).Value = doNotProceed;
                command.Parameters.Add("@reason", SqlDbType.VarChar).Value = reason;
                command.Parameters.Add("@option", SqlDbType.VarChar).Value =  Option;
                [B]command.Parameters.Add("@oamt", SqlDbType.Money).Value = Double.Parse(OAmt);[/B]
                command.Parameters.Add("@osdate", SqlDbType.DateTime).Value = Osdate;
                command.Parameters.Add("@oedate", SqlDbType.DateTime).Value =  Oedate;

                command.ExecuteNonQuery();
                db.closeConnection();
            }
        }

what is the error in my code. w@ should i do to avoid this

thanxxxxxxxxxxxx

Dani AI

Generated

The FormatException happens because Parse/Double.Parse/Decimal.Parse throws when the input text is empty or contains non‑numeric characters from the mask (currency sign, thousands separators or prompt characters). , the safest approach is to (a) read the masked value in a raw form, (b) try to parse it with NumberStyles that accept currency characters, and (c) pass either a decimal value or DBNull.Value to the parameter so the database call never sees an empty string.

A compact pattern to use (handles empty input, “$”, commas, parentheses, culture, and avoids exceptions):

using System.Globalization;

// get the user text without mask literals if using MaskedTextBox
maskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
string raw = maskedTextBox1.Text;

decimal parsed;
object dbValue;

if (string.IsNullOrWhiteSpace(raw) ||
    !decimal.TryParse(raw, NumberStyles.Currency | NumberStyles.AllowThousands,
                      CultureInfo.GetCultureInfo("en-US"), out parsed))
{
    dbValue = DBNull.Value;           // or use 0m if you prefer zero
}
else
{
    dbValue = parsed;
}

command.Parameters.Add("@tamt", SqlDbType.Money).Value = dbValue;

A few practical notes: was right to prefer decimal over double — decimal avoids rounding surprises for money. Prefer TryParse with NumberStyles.Currency instead of manual Replace("$", ...) so the parser accepts locales, commas and parentheses automatically. If you want fixed scale, use SqlDbType.Decimal and set Precision/Scale on the SqlParameter before assigning Value. Finally, check MaskedTextBox.MaskCompleted (or TextMaskFormat) to avoid reading incomplete input. These checks will stop FormatException and make the DB insert robust.

Recommended Answers

All 2 Replies

You should remove the "$" sign from the text. And also, it is recommended to use Decimal data type for Money.

To remove the "$" you can use Replace() method:

command.Parameters.Add("@tamt", SqlDbType.Money).Value = [B]Decimal[/B].Parse(Amt.Replace("$", string.Empty);

command.Parameters.Add("@oamt", SqlDbType.Money).Value = [B]Decimal[/B].Parse(OAmt.Replace("$", string.Empty);

Thanks

You should remove the "$" sign from the text. And also, it is recommended to use Decimal data type for Money.

To remove the "$" you can use Replace() method:

command.Parameters.Add("@tamt", SqlDbType.Money).Value = [B]Decimal[/B].Parse(Amt.Replace("$", string.Empty);

command.Parameters.Add("@oamt", SqlDbType.Money).Value = [B]Decimal[/B].Parse(OAmt.Replace("$", string.Empty);

Thanks

hey,
but when the value is empty how can i hadle it . when the value is empty it gives an Exception saying Format Exception was unhandled, input string was not formatted correctly. how can i handle this situation

thanxxxx.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.