Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Error on ExecuteScalar() - NullReferenceException

Status
Not open for further replies.

rnooraei

Programmer
Apr 5, 2005
74
CA
Here is the code
Dim SqlMetroDateMin As String = "select top 1 Format(E13A101.TIME, 'yyyy/mm/dd')AS tmin from E13A101 where fmin=(select min(fmin) from E13A101 where month(TIME)= " & ddlMonth.SelectedValue & " and year(TIME)= " & ddlYear.SelectedValue & " ) and month(TIME)= " & ddlMonth.SelectedValue & " and year(TIME)= " & ddlYear.SelectedValue
Dim cmd As New OleDbCommand(SqlMetroDateMin, conn)
conn.Open()
lblDateMin.Text = cmd.ExecuteScalar().ToString()
conn.Close()

if there is no min date, I will get NullReferenceException error. I was wondering how can I check for the null before I run cmd.ExecuteScalar().ToString command.

Thanks
 
You'd have to run another query to do that.
First I suggest you use stored procedures
Second, you can use ISNULL and a case statement to avoid the error.
 
1. Always use parameterized queries. they are secure. they are easier to read. they are more dynamic (refactoring to reusable code)
2. don't format the date on the database, just get the value. formatting is for user presentation only.
3. use a better query.
Code:
select	top 1 TIME AS tmin  
from	E13A101 
where	month(TIME)= @mont and year(TIME)= @year
order by fmin desc
finally check for a dbnull value 1st. then set the value.
Code:
conn.Open()
object possibleDate = cmd.ExecuteScalar();
conn.Close()

if(!(possibleDate == null) && (possibleDate == DbNull.Value))
   lblDateMin.Text = possibleDate.ToString();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top