0

I am making a web form which deletes the selected id from the database. But whenever I run my command I get the following error

NullReferenceRxception was unhandled by the user.

And I'm getting this where I'm using addwithvalues.

This is my code:

con.Open();
string query = "delete from [User] where id ='" + TextBox1.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@id", TextBox1.Text); //this is giving an error
int UserExist = (int)cmd.ExecuteScalar();
if (UserExist > 0)
{
    cmd.ExecuteNonQuery();
    con.Close();
}
else
{
    Label1.Text = "No such id found ";
}

How can I fix this error?

sinsedrix
  • 3,341
  • 3
  • 20
  • 38
JustCurious
  • 641
  • 1
  • 7
  • 23
  • Are you sure the same id that you put in your textbox exits in your database? have you traced your code? Try this as well `TextBox1.Text.Trim()` – Masoud Andalibi Feb 21 '17 at 07:12
  • What is the Type of id in your database? – Masoud Andalibi Feb 21 '17 at 07:17
  • [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](https://xkcd.com/327/) – marc_s Feb 21 '17 at 07:40
  • I am not an sql expert but if the problem really is in the line OP marked, does it even matter what is in the db or which type `id` is? Does `AddWithValue` access the db in any way? Couldn't the problem simply be that there is no `@id` in the query? (Which your answer solves, of course) @Valkyriee – wkl Feb 21 '17 at 07:46
  • @wkl yeah it can work that way as well. but this eliminates any unwanted data to be added as Id, a validation before sending to database. – Masoud Andalibi Feb 21 '17 at 07:51
  • @wkl here in delete it doesnt really matter, but in insert it'll be very useful ^^ – Masoud Andalibi Feb 21 '17 at 07:59
  • Mark as answer if this was the answer you looked for – Masoud Andalibi Mar 07 '17 at 07:30

1 Answers1

0

Use this approach see if its works, i assumed the type of Id is an Integer

using(var cmd1 = new SqlCommand("DELETE FROM User WHERE Id = @Id", conn))
{
    cmd1.Parameters.Add("@Id", SqlDbType.Int).Value = Int.Parse(TextBox1.Text);
    conn.Open();
    cmd1.ExecuteNonQuery();
}
Masoud Andalibi
  • 2,755
  • 4
  • 13
  • 35