0

My sql command is throwing null reference exception in asp dot net using c#

This is my code :

SqlConnection cn = new SqlConnection("server=.;database=online_blog;integrated security=true");
cn.Open();

SqlCommand cmd3 = new SqlCommand("UPDATE profiles SET fname = '" + TextBox5.Text + "', lname = '" + TextBox6.Text + "', logname = '" + TextBox7.Text + "', dob = '" + TextBox10.Text + "', highsc = '" + TextBox8.Text + "', coll = '" + TextBox9.Text + "', country = '" + TextBox11.Text + "', state = '" + TextBox12.Text + "', hometown = '" + TextBox13.Text + "', languages = '" + TextBox14.Text + "', aboutme = '" + TextBox15.Text + "', gender = '" + RadioButtonList1.SelectedValue + "', photo = '" + Session["photo"].ToString() + "' where logname = 'saraf' ", cn);


    try
    {
        cmd3.ExecuteNonQuery();
        Response.Write("       New Account Updated");
        Session["username"] = TextBox7.Text;
    }
    catch
    {
        Response.Write("\nerror occured");
    }
    cn.Close();

Session ["photo"] is initialised....so dont worry about that

The line in which i m creating the new SqlCommand is Throwing Exception

5
  • 6
    This code is like pornography. Have you heard of proper variable naming? Have you heard of SQL injection? Have you heard of parametrized queries? Have you heard of how questions should be asked on StackOverflow? Judging from your post I guess the answer is no to all those questions. Commented Jul 9, 2011 at 19:30
  • 2
    That code is extremely dangerous. Darin is 100% correct - will look, but you must parameterise/ Commented Jul 9, 2011 at 19:34
  • @Darin: good one, @ Sourav: maybe RadioButtonList1.SelectedValue is null Commented Jul 9, 2011 at 19:36
  • 1
    Good example on how the code should not be written. Commented Jul 9, 2011 at 19:45
  • @Maziar that won't cause an error - you are allowed to concatenate null. Commented Jul 9, 2011 at 19:47

1 Answer 1

4

from your description of the line that is throwing, one of the UI elements is not initialized. Which one? Only you can find out - set a breakpoint and debug it. Hover over all the components until you find the null.

But that really is very bad code:

  • mixing UI, data access, session and response all at once (separation of concerns)
  • concatenation of user input is a massive security risk (SQL injection)
  • no using statements for the connection/command (risk of pool saturation)
  • crude error handling (that will stomp on any UI)
  • the names... How about username.Text - do you see how that is clearer?
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.