Guys I need a little help. This is my first time developing an app that has DB in it, considering this, please forgive my blunders.

I am trying to obtain a boolean value from database and applying if, else loop on it...but it keeps throwing "Object reference not set" error on ExecuteScalar function.

Here is the code :-

        string sql = " // here is my sql query ";
        string connectionstring = " // Here is my connection string.... ";
        SqlConnection connection = new SqlConnection(connectionstring);
        SqlCommand command = new SqlCommand(sql,connection); 
        command.Connection = connection;
        connection.Open();
        bool ev = (bool)command.ExecuteScalar();
        if (ev == true)
        {
            MessageBox.Show("some error");
        }
        else
        {
            // Some Code
         }

What am I doing wrong?

Help will be really appreciated.

Regards.

有帮助吗?

解决方案

Probably the query returns null. Try this:

bool? ev = (bool?)command.ExecuteScalar();

if(ev.GetValueOrDefault(false))
{
   MessageBox.Show(...);
}

The ? means nullable, so it this way the value returned from the query is allowed to be null.

其他提示

do some validation for the ExecuteScalar return value as below

using(SqlConnection connection = new SqlConnection(connectionstring))
using(SqlCommand command = new SqlCommand(sql,connection)) 
{
    connection.Open();
    object ev = command.ExecuteScalar();
    bool flag; 
    if(ev!=null)
    {
       // return as null value, do Task 1 
    }else if(Boolean.TryParse(ev.ToString(), out flag) && flag)
    {
       // return as true value, do Task 2   
    }
    }else
    {
       // return as false value, do Task 3   
    }
}

Patrick's comment was spot on. Here is a complete example...

string sql = " // here is my sql query ";
string connectionstring = " // Here is my connection string.... ";

using (SqlConnection connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(sql,connection)) 
{
    connection.Open();
    bool? ev = (bool?)command.ExecuteScalar();

    if (ev.HasValue == true && ev.Value == true)
    {
        MessageBox.Show("some error");
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top