.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

How do I check if my ExecuteScalar() is null?

Posted By:      Posted Date: October 22, 2010    Points: 0   Category :ASP.Net

Hi all,

I know for a fact that the SQL statement below returns NULL but my code statement "if (obj != null)" is not working.
When I debug it I see a value of {} ... not sure what that is. Here is my code:

protected string GetLatestTimeStamp()
	DateTime latestTimeStamp1 = DateTime.UtcNow;
	string latestTimeStamp2 = String.Empty;

	string select = "select max(timeStamp) from dbo.JobHistory";

	SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
	SqlCommand cmd = new SqlCommand(select, conn);

		object obj = cmd.ExecuteScalar();

		if (obj != null)
		latestTimeStamp1 = (DateTime)obj;
		latestTimeStamp2 = latestTimeStamp1.ToString("yyyy-MM-dd HH:mm:ss.fff");
	return latestTimeStamp2;

So, even if SQL returns NULL, it still validates obj as NOT NULL !!! :(

Any ideas? Thank you!

View Complete Post

More Related Resource Links

How to check for null/empty strings on dynamic objects?


What is the proper way to check for null or empty strings on dynamic objects? This is the only solution I've found so far:

if (admin.PasswordHash.GetType() == typeof(DBNull) || admin.PasswordHash == string.Empty)

If the field is null, the object returned is DBNull.Value, but if the field is empty string, it's return as a System.String object. This makes it impossible to do regular "admin.PasswordHash == DBNull.Value" check, as that will fail whenever the field has been set to empty string. Is my example the right (and only) way to go?

SSRS 2005 + Null check box + change Label 'NULL'

Hi, My management asked me if I can change the label of NULL check box for report parameters. They said that users may not understand 'NULL' label means. Is it possible to do. When I searched, some said it can be done by creating custom control and registering it in GAC etc. I appreciate your response. Thanks, Spunny

How do I check if ExecuteScalar() returned me any rows when you are using casting this way...


Hi all

The code below works fine if I have records on my table but if the table is empty I get the following error:

latestTimeStamp1 = (DateTime)cmd.ExecuteScalar(); <=== {"Specified cast is not valid."}

So I am trying to add an IF statement to check if there was any return from ExecuteScalar() method.
How can I verify if something was returned or how can I prevent this cast error from happening?
I managed a workaround by using DataTable and checking if table was null but I need this code to have less overhead as possible since I will be pulling up this timeStamp date all the time.

 DateTime latestTimeStamp1 = DateTime.UtcNow;
 string select = "select max(timeStamp) from Table1";

 SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Test"].ConnectionString);
		 SqlCommand cmd = new SqlCommand(select, conn);

	//if ExecuteScalar returns something 
	 	latestTimeStamp1 = (DateTime)cmd.ExecuteScalar();
		return latestTimeStamp1;
 catch (Exception ex)

Thank you

SQL CE 3.5 Null Parameter Check



I cannot find a definitive answer for a very simple question. In SQL CE 3.5, I am attempting to execute the following:

            using (var connection = new SqlConnection(""))

                using (var command = connection.CreateCommand())

                    command.CommandType = CommandType.Text;
                    command.CommandText = "Select * From County Where CountyId = Coalesce(@Id,3)";
                    var dbParameter = command.CreateParameter();
                    dbParameter.ParameterName = "@

C# How to check prammatically if null value exists in database table (using stored procedure)?


How to programattically check if null value exists in database table (using stored procedure)?

I know it's possble in the Query Analyzer (see last SQL query batch statements)?

But how can I pass null value as parameter to the database stored procedure programattically using C#?

Although I can check for empty column (the following code passes string.Empty as parameter but how to pass null value?), I cannot check for null value in the following code snippet:

SQL Queries:

USE [master]

IF EXISTS (SELECT name FROM sys.databases WHERE name = 'ExampleDatabase')
DROP DATABASE [ExampleDatabase];

CREATE DATABASE [ExampleDatabase];

USE [ExampleDatabase];

DROP TABLE dbo.ExampleTable;

IsActive BIT,


How to check if session is null or not in C#



 Like to know the syntax to check Session is null or not in C#

Could be something like this....

if(Session["mysession"] == null)


Do something








Check For Null Values


When using an Access database I had to check text fields for null (which is accepable in my program) withcode like this:


If IsDBNull(oData.dr.Item("Media")) = False Then cboMedia.Text = oData.dr.Item("Media")

I am converting my program to SQL Server and this 'Seems" no longer necessary and this line of code seems to work:

cboMedia.Text = oData.dr.Item("Media"<

Check for Null Value or Spaces


I would like to check field FirstName if it's a null field or if the field has spaces in it.

My FirstName field sometime is NULL or it has spaces in it.

I would like to check for those two scenario.


Using a CompareValidator to check input is a valid date

The CompareValidator can do more than just compare two controls. You can also compare it against several of the main .net data types such as Date, Integer, Double and Currency.

To do this you would set Operator="DataTypeCheck" and instead of setting the ControlToCompare or ValueToCompare attributes as you normally would you use the Type="Date" (or any of the data types I have listed above).

Check All with JQuery and a Asp.Net GridView

Display a Grid on the screen with a checkbox in each row. At the bottom of the page have "Check All" button.

Typically if I need to do anything interesting I use a template column. So my GridView will look like the one below (most other columns removed for readability). The only interesting point to note is the CssClass="ApprovalCheckBox" in the CheckBox ItemTemplate.

check box control


Hi ,

I have a three check box in my web form ,i need to choose only one check box, if i choose one check box

another 2 check box automatically unchecked

can i use jquery for check box

I thought this would be simple... Trying to create a login does an ajax check before submit


I have the standard .net login control that is working.  (Still learning .net after 15yrs of classic)

What I want to do is OnButtonClick run a javascript function (to do an ajax call to the db to check if login is valid or not) and if it returns true, then submit the form normally, else don't submit. The piece that I can't figure out, is how to correctly override the default click even to hit my JS routine and then submit the form properly afterwards.

Thanks ahead of time

how to check a textbox value in jquery?



I want to perform some action when an asp.net textbox value length is greater than 1 character. And for this I wanted to know how to write this check in jquery?

I have created a check like below-

if ($('[id=txtUserInput]').val().length > 2)
{ do some work...} 

But its giving me the following error

$("[id=txtUserInput]").val() is undefined

Can anybody let me know the right way of doing this?



Automatically redirect to HTTPS and check if SSL is active



I've set in the web.config:

    <!-- User Authentication -->
    <authentication mode="Forms">
      <forms loginUrl="~/Page/View/Content/Login.aspx" timeout="2880" requireSSL="true" />

This works fine. If there is no ssl connection, the login form doesn't continue. But I would like to check if ssl is active (in codebehind) and, if it's possible, to automatically the user to the https page if he's currently on http. (I could do this job by manually redirect with page.response("https://url.../login.aspx"); but this is not really generic. For example if the webapp is moved to another domain it doesn't work anymore... I'm looking for something like: FormsAuthentication.RedirectWithSSL(); or so... :D)


Users getting logged out because HttpContext.Current is null


We've  been trying to fix this one for a couple years, and I'm just out of ideas, so any help is really appreciated!

We've got a fairly large, complex web application that uses Forms Authentication to authenticate users.  Throughout the application we store and retrieve information about users in the Session object, and in some cases in cookies.  In a couple places we check for the existence of the context, and if it's null we send the user back to the login page to re-establish the session. 

Just a quick run-down of this web app: C#, .NET 3.5, IIS 6, ASP.NET State Service to manage session

As for the session timer, we use our own home-grown timer, which is basically a client-side timer, which is backed up by a check to the SQL database to see when their last activity was.  This seems to work well for us.  It's not perfect, but it allows us to notify the user before the session times out, and allows us to be certain we're not logging a user out before their 60 minutes of inactivity is up.

What's happening is that certain users are being logged out after just a few minutes.  We've eliminated the timer as a cause and believe what's happening is the HttpContext.Current is null, so the user is logged out.  We do not know why the HttpContext.Current is null, and I underst

how to check which pages of my site that my visitor visiting at the moment


 Hi all, and thanks a lot for the replies since now. I have a new question :

I prepared a simple instant messaging system for my web site and i would like to learn which visitor (registered member) is at which page of my site. 

For example : 

Uid:10000, Username:donald, NameSurname:Donald DUCK is a registered and signed in visitor.

I need the code which tells me that visitor is at which page (ie. images.aspx?imageid=143223)

Sorry for my poor english, and let me know if i should explain more clearly :)

Have a good evening...

Tools for memory error check in VS2005


Dear all,

I am going to write vs2005 program with ASP.NET and C++.

As you know that C++ will involve a lot of memory error handling.

Do you know is there any tools for checking memory error in Code Behind C++??

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend