0

I am implementing a standalone application using C#. But I am getting an error when clicking the insert button. How can I resolve this?

Code:

try
{        
  con.Open();
  String insert_query = "INSERT INTO Items(Item_Number, Total_Item,Item_Name, Price,Category)" + 
       "VALUES("+ int.Parse(textBox2.Text) + "," +
                  int.Parse(textBox3.Text) + ",'" +
                  textBox4.Text+ "'," +
                  int.Parse(textBox5.Text) + ",'" +
                  comboBox1.Text+"')";
  SqlDataAdapter SDA = new SqlDataAdapter(insert_query, con);
  SDA.SelectCommand.ExecuteNonQuery();

  MessageBox.Show("Add Success! ");
}
catch (Exception ex)
{
  MessageBox.Show("Error" + ex);
}
finally
{
  con.Close();
}

Error:

ErrorSystem.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyle options, NumberBuffer& number, NumberFormatinfo infi, Bollean parseDecimal) at System.Number.Parseint32(String s, NumberStyle style, NumberFormatinfo info

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
trojen_dev
  • 35
  • 7
  • I suggest you that try to use `SelectCommand.Parameters.Add()` instead of concatenate string for query. See [How can I add user-supplied input to an SQL statement?](https://stackoverflow.com/questions/35163361/how-can-i-add-user-supplied-input-to-an-sql-statement) – Selim Yildiz Mar 16 '20 at 06:13
  • Your code is wide open to being hacked using sql injection. Learn to use parameterized queries **now** to avoid this. – Chris Dunaway Mar 16 '20 at 16:09

1 Answers1

4

Use from TryParse instead of parse because if string format not be valid and it be a word, parse can not do that and throw exception But TryParse return false if error occured.

bool res=int.TryParse("11", out number))---->res=true
bool res=int.TryParse("aa", out number))---->res=false
//or
int res=int.parse("11") -->it is ok
int res=int.parse("ff") //it is error and throw exception

You should check your input text entered format that be number in your textbox's

Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28