0

I get this error:

Input string was not in a correct format.

from my code shown below. I want to delete a row in my database just with click on a button.

 SqlConnection conn = new SqlConnection(@"DataSource=.\SQLEXPRESS;
     AttachDbFilename=C:\Users\Mr\Documents\Student.mdf;
     Integrated Security=True;Connect Timeout=30;User Instance=True");

SqlCommand cmd = new SqlCommand();

int x = Convert.ToInt32(table2DataGridView.SelectedCells[0].Value);

cmd.Parameters.Clear();
cmd.Connection = con;
cmd.CommandText = "delete from Table2 where name=@N";
cmd.Parameters.AddWithValue("@N", x);

con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Removed");

I get the error on the first line.

@N is my first textbox that I can put name on that.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Ehsan
  • 3
  • 1
  • 3
    I don't think your first line generates `FormatException`. I think it is generated on `int x = Convert.ToInt32...` line. What is the value of `table2DataGridView.SelectedCells[0].Value` exactly? Debug your code and tell us. And what is your `CurrentCulture`? – Soner Gönül Oct 12 '14 at 17:06
  • Don't use the `AttachDbFileName=` and `UserInstance=true` features anymore - they cause a lot of confusion and grief, and will be removed from SQL Server in a future version anyway - better stay away from it today already! See Aaron Bertrand's excellent blog post [Bad habits to kick: Bad habits : Using AttachDBFileName](http://blogs.sqlsentry.com/aaronbertrand/bad-habits-attachdbfilename/) for more background info on this. – marc_s Oct 12 '14 at 17:15
  • You did not get an error. You got an _exception_. Do yourself a big favor and learn about exceptions. In particular, when you post a question about an exception, you need to post the _complete_ exception. You can get the complete exception by surrounding your code with `try {//code} catch(Exception ex){MessageBox(ex.ToString()); throw;}` – John Saunders Oct 12 '14 at 19:03

2 Answers2

0

Replace

int x = Convert.ToInt32(table2DataGridView.SelectedCells[0].Value);

with

string x = table2DataGridView.SelectedCells[0].Value.ToString();

Query should work with this.

zkanoca
  • 9,664
  • 9
  • 50
  • 94
-1

you can also use

cmd.Parameters.AddWithValue("@N", x.ToString());