user3438545
user3438545

Reputation: 1

Database connection ;Null Reference Exception error in ASP.net

I understand that many similar questions have been asked. I've looked through them and after several days, I still couldn't understand where I have gone wrong with my code. I'm a beginner, so please bear with me if I seemed a little silly.

Here is the problem I am facing. I am trying to create a simple asp.net registration page that will insert records into a database (on SQL server). I have five text boxes on my web form, namely

I have a class file that is written this way

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

public class Student 
{
private static string connStr = "server = localhost; initial catalog = DevelopTest; integrated security = true;";

public static void AddUser(string username, string password, string email, string question, string answer)
{
    string sqlStr = "INSERT INTO Student VALUES(@username, @pass, @email, @question, @answer, 1);"; 
    SqlConnection dbConn = new SqlConnection(connStr);
    SqlCommand sqlComd = new SqlCommand(sqlStr, dbConn);
    sqlComd.Parameters.AddWithValue("@username", username);
    sqlComd.Parameters.AddWithValue("@pass", password);
    sqlComd.Parameters.AddWithValue("@email", email);
    sqlComd.Parameters.AddWithValue("@question", question);
    sqlComd.Parameters.AddWithValue("@answer", answer);

    SqlTransaction tran = null;
    try
    {
        dbConn.Open();
        tran = dbConn.BeginTransaction();
        sqlComd.Transaction = tran; 
        sqlComd.ExecuteNonQuery();
        tran.Commit();
    }
    catch (SqlException e)
    {
        tran.Rollback();                        
    }
    finally
    {
        if (dbConn != null) { dbConn.Close(); }
    }


}

And then I have the button click written this way:

protected void btnRegister_Click(object sender, EventArgs e)
{
Student.AddUser(tbUsernameRegs.Text, tbPassRegs.Text, tbeMailRegs.Text, tbSecretQnsRegs.Text, tbSecretAnswRegs.Text);
}

When I click one the button though, I get a null object reference exception. I understand that null object reference means I have an uninitialised object, but I've been trying to spot the mistake for days already, and still couldn't figure out where I have gone wrong.

I hope could help me out on this. Thanks a lot.

Edit* Here's the stack trace.

[NullReferenceException: Object reference not set to an instance of an object.]
Student.AddUser(String username, String password, String email, String question, String answer) +290
Registration.btnRegister_Click(Object sender, EventArgs e) +94
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9752490
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +196
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Upvotes: 0

Views: 3304

Answers (2)

DRapp
DRapp

Reputation: 48139

Couple small things. You should be explicit about the columns you are inserting and should never assume they are going in proper order... qualify the insert...

insert into student ( UserName, Password, EMail, Question, Answer, FlagField )
   values ( @username, @pass, @email, @question, @answer, 1 )

What would happen if the table had columns as Password, Email, UserName, then the columns would not be properly paired up.

Sorry on the ToString() suggestion, brain-cramp. Anyhow, it is throwing error based on inbound parameter string although expected passed as NULL. You will need to validate them coming in, such as

if( username == null)
   username = "";
if( pass == null )
   pass = "";
etc...

THEN, apply your .Parameters.AddWithValue() call

Upvotes: 0

Andrei
Andrei

Reputation: 56688

In the catch block you are calling

tran.Rollback();

without checking if tran is not null. And it might be if the connection attempt fails and no transaction was created here:

dbConn.Open();
tran = dbConn.BeginTransaction();

So add checking for null for tran variable:

catch (SqlException e)
{
    if (tran != null)
    {
        tran.Rollback();                        
    }
}

Upvotes: 4

Related Questions