hello!
i am facing an error ("object refrence is not set to an instance of an object.") i check my all code but i can able to solve it . here is a line of code where i getting it.

.
.
.
cmd = new sqlcommand(_mycommand_)

if (__mycondition)
{
serialNo = convert.ToInt16(cmd.executeScalar().toString());//----here i got an error
// as serialNo is a variable defined publicaly in my struct and datatype of it is int
}

please help me in this , so that i can move forword.

Best regards

put .ExecuteScalar instead of .executeScalar (use a capital E)

Why are you doing:

convert.ToInt16(cmd.executeScalar().toString());

take off the .toString() (plus its To.String()), convert it straight to string and put a capital C on convert.

Hope this helps

"object refrence is not set to an instance of an object."

Cause 1:
Not declaring variables!

Yes, I know it sounds obvious, but MAKE SURE that you've explicity declared the variable, and don't forget to use the appropriate scope!

Cause 2:
Bad scoping

public Form1()
{
    private string strHello;
}


 private void btnOpen_Click(object sender, EventArgs e)
        {            
            strHello = "Hello";
            Textbox.Text = strHello;
        }

This won't work because strHello is only accessable in Form1()

If anybody knows more please let me know, thanks.

You need to make sure your command is actually returning some data. There is a pretty good chance that it isn't (hence the null reference exception caused by trying to convert a null reference to an int16).

If this is the case, I recommend checking for nulls and having a fall-back default value or some type of exception handling in place.

If your SQL is returning something that cannot be converted, that can be a problem.
What was the exact error you received?

Instantiate your struct which has serial no as a variable and then access the serial number using the object of that struct. the struct has not been initialised, hence you are getting "object refrence is not set to an instance of an object." exception. try this out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.