Solved

c# - Error -> Object reference not set to an instance of an object.

Posted on 2009-05-19
6
1,324 Views
Last Modified: 2013-12-17
Hi experts,

     I am using C# and Mysql in my project. I have pasted my sp and C# code in the below box.

     I am returning a Int value from my SP. From c# i have to get that value, which determines whether the user has logged in or not.

     My sp works fine, when i executed it in my Mysql query browser and it also returns a perfect value.

     Problem is with my c# code to retrieve that value.
     I am getting this error :
     Object reference not set to an instance of an object.
     in the line "doesExist = (int)cmd.ExecuteScalar();"
     [Please refer the code.]

     Please help me on this. Its very URGENT....
SP :

-------------------------------------------------------------------------------
 

DELIMITER $$
 

DROP PROCEDURE IF EXISTS `demo`.`sp_LoginCheck`$$
 

create PROCEDURE `demo`.`sp_LoginCheck`( 

 IN UserName1 varchar(50),

 IN Password1 varchar(50),

 OUT DoesExist int)   

    BEGIN

 declare userCount INT default 0;

 SET DoesExist = 0; -- set to false initially, we'll assume for now it doesn't exist

 SELECT COUNT(Uid) INTO userCount

 FROM tbl_Users

 WHERE username = username1 and password=password1;

 IF userCount > 0 THEN

  SET DoesExist = 1;  -- more then one returned, return true

 END IF;

    END$$
 

DELIMITER ;
 

-------------------------------------------------------------------------------
 

C# :

-------------------------------------------------------------------------------

  public static int CheckLogin_Instructor(string UserName, string Password)

        {

            int doesExist = 0;

            try

            {

                MySqlConnection myConn = new MySqlConnection(ConfigurationSettings.AppSettings["Con"]);

                MySqlCommand cmd = new MySqlCommand("sp_LoginCheck", myConn);

                cmd.CommandType = CommandType.StoredProcedure;

                MySqlParameter param = new MySqlParameter();

                param = cmd.Parameters.Add("@UserName1", MySqlDbType.VarChar, 50);

                param.Value = UserName;

                param = cmd.Parameters.Add("@Password1", MySqlDbType.VarChar, 50);

                param.Value = Password;

                param = cmd.Parameters.Add("@DoesExist", MySqlDbType.Int32);

                param.Direction = ParameterDirection.Output;

                myConn.Open();

                doesExist = (int)cmd.ExecuteScalar();

                myConn.Close();

            }

            catch (Exception ex)

            {

                ExceptionHandler.writeToLogFile(ex.StackTrace.ToString());

            }

            return doesExist;

        }

-------------------------------------------------------------------------------

Open in new window

0
Comment
Question by:srk1982
6 Comments
 
LVL 9

Assisted Solution

by:tculler
tculler earned 165 total points
ID: 24428238
Are you sure the that...
- The exception has a StackTrace at all?
- Neither parameter is null?
0
 
LVL 12

Assisted Solution

by:needo_jee
needo_jee earned 165 total points
ID: 24428244
hi
if you want to use cmd.ExecuteScalar()

write this as a last line in your SP
SELECT DoesExist AS  DoesExist

OR

however, if you want to use Output parameter then you can use execute scaler in the way you have used.
you need to get output parameter value after you execute query , not form scaler

after this line
cmd.ExecuteNoneQuery()

 doesExist = (int)cmd.Parameters["@DoesExist"].value

-thanks


0
 

Author Comment

by:srk1982
ID: 24428275
Hi tculler,

           There are 2 input parameters Username and Password.
           They are not null.
 
           The error is null reference exception, "Object reference not set to an instance of an object." which means that the return value is not coming from the SP [I guess]

Because the way i am executing the SP in mySql is
--------------------------------------------------------------
call sp_LoginCheck ('srk2','pwd2',@DoesExist);
SELECT @DoesExist
--------------------------------------------------------------

I think there is something to do with SP !!!
Correct me if i am wrong. I am a newbie for Mysql and C#.


 
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:srk1982
ID: 24428311

Hi needo_jee,

If i use your both idea i am getting the following error :

System.ArgumentException: Parameter 'string' not found in the collection.

Thanks.
0
 
LVL 8

Accepted Solution

by:
tony_angelopoulos earned 170 total points
ID: 24428368
I've had problems with this as well and noticed that when casting, all does not always go as planned.  cmd.ExecuteScalar() returns an object, and sometimes that object is NULL.  I've gotten around this before with using something like

object scalar = cmd.ExecuteScalar();
int retval = scalar.HasValue==false?0:Convert.ToInt32(scalar);

(if I remember my inline if statments correctly)
0
 

Author Closing Comment

by:srk1982
ID: 31583335
Hi guys,

           I changed the way i am doing. I am getting the value in a dataset and accesing that in my code.
  Thanks for assisting me... I am sharing the points with all the 3 guys assisted me.

Thanks again.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now