0

I am using a SqlCommand to insert values in a row of a SQL Server table. It works perfectly fine when I insert a text to all my textbox but whenever there is a blank textbox, I always get this error

Input string was not in a correct format

Here is my code

private void BtnSubmit_Click(object sender, EventArgs e)
{
  try
  {
    if (MessageBox.Show("Are you sure you want to save this book?", "Saving Record", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
      cn.Open();

      cm = new SqlCommand("INSERT INTO tblBook (bkISBN, bkTitle, bkEdition, bkGenre, bkMediaType, bkLanguage, bkAuthor, bkPublisher, bkPrice, bkDate) VALUES (@ISBN, @booktitle, @edition, @genre, @mediatype, @language, @author, @publisher, @price, @date)", cn);
      cm.Parameters.AddWithValue("@ISBN", txtISBN.Text);
      cm.Parameters.AddWithValue("@booktitle", txtTitle.Text);
      cm.Parameters.AddWithValue("@edition", txtEdition.Text);
      cm.Parameters.AddWithValue("@genre", txtGenre.Text);
      cm.Parameters.AddWithValue("@mediatype",cboMediaType.Text);
      cm.Parameters.AddWithValue("@language", txtLanguage.Text);
      cm.Parameters.AddWithValue("@author", txtAuthor.Text);
      cm.Parameters.AddWithValue("@publisher", txtPublisher.Text);
      cm.Parameters.AddWithValue("@price", int.Parse(txtPrice.Text));
      cm.Parameters.AddWithValue("@date", dtCreated.Text);

      cm.ExecuteNonQuery();
      cn.Close();

      MessageBox.Show("Record has been successfully saved!");
      Clear();
      frmlist.LoadRecords();
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

Any help to fix this will be appreciated. Thank you.

1
  • Is Price meant to be an integer value from a textbox? Usually prices are SqlDbType.Money/System.Decimal or Integer Cents (i.e. parsed decimal value multiplied by 100) . Commented Mar 14, 2020 at 7:47

1 Answer 1

2

Here's your problem line:

cm.Parameters.AddWithValue("@price", int.Parse(txtPrice.Text));

The Int32.Parse method will throw a FormatException if it cannot parse the value.

Use Int32.TryParse (with appropriate CultureInfo!) instead:

cm.Parameters.AddWithValue("@price", Int32.TryParse( txtPrice.Text, CultureInfo.CurrentCulture, NumberStyles.Currency, out Int32 priceValue ) ? priceValue : DBNull.Value);

That said, don't use AddWithValue!

Sign up to request clarification or add additional context in comments.

1 Comment

I am new to programming and I'll try to practice not using AddWithValue when inserting a value. Thank you so much for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.