Converting null string to date - asp.net

I have searched high and low to no avail, and this is last step before completing my project so please help! Thanks in advance!
The user will select an entry in a gridview, which then redirects them to a form that is populated with the data from the selected row (thus making the gridview editable in a more user friendly way). Null values are accepted by the DB and I would like to show null date values as blank (or " ") in the corresponding text boxes. Instead I get the error:
Conversion from type 'DBNull' to type 'Date' is not valid.
Here is my code:
'preceded by connection code
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = #recnum"
'Dim sqlCmd As New OleDb.OleDbCommand("SELECT * from Master WHERE RecNum = #recnum", connection)
Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection)
FileCommand3.Parameters.AddWithValue("#recnum", user)
Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader()
If Reader3.Read Then
stock = myCStr(Reader3("StockNum"))
make = myCStr(Reader3("Make"))
color = myCStr(Reader3("Color"))
stockin = myCStr(Reader3("Stockin"))
ucistart = myCStr(Reader3("UCIStartDate"))
repairs = Reader3("Repairs")
tires = Reader3("tiresneeded")
onlot = Reader3("onlot")
sold = Reader3("sold")
year = myCStr(Reader3("year"))
model = myCStr(Reader3("model"))
location = Reader3("location")
srvcRO = myCStr(Reader3("svcROnum"))
ucicompldate = myCStr(Reader3("uciestcompletedate"))
collRO = myCStr(Reader3("collisionROnum"))
other = myCStr(Reader3("other"))
offprop = Reader3("offProperty")
detail = (Reader3("detail")
End If
connection.Close()
SoldCheckBX.Checked = sold
DetailTXTbox.Text = detail
'etc, etc
End Sub
I used the function mycstr to fix the dbnull to string error but it does not seem as simple to adapt to "date" data type
Function myCStr(ByVal test As Object) As String
If isdbnull(test) Then
Return ("")
Else
Return CStr(test)
End If
End Function

try this when you read the values from the reader with all your dates, this will first test to see if the date is dbnull, if it is then it will assign a nothing value and you should get your desired empty cell, otherwise it will show the date:
ucistart = IIf(reader3("UCIStartDate") Is DBNull.Value, Nothing, reader3("UCIStartDate"))

Have you tried using the Convert.IsDBNull function?
Here is the official documentation.

Related

How can I calculate number of days between 2 dates?

I have a reservation page and a reservation table which contains reservationstart column, reservationend column and numofdays column.
I have determined the number of days between the two dates which a client will select but nothing was stored in the table when I update.
The data type of numofdays was datatime but I have changed this to int.
I used this first, to declare the start and end date:
DayPilotScheduler1.Scale = TimeScale.Manual
Dim start As New Date(Date.Today.Year, 1, 1, 12, 0, 0)
Dim [end] As Date = start.AddYears(1)
This is the code for the update:
Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
Dim id_Renamed As String = e.Value
Dim start As Date = e.NewStart
Dim [end] As Date = e.NewEnd
Dim resource As String = e.NewResource
Dim message As String = Nothing
If Not dbIsFree(id_Renamed, start, [end], resource) Then
message = "The reservation cannot overlap with an existing reservation."
ElseIf e.OldEnd <= Date.Today Then
message = "This reservation cannot be changed anymore."
ElseIf e.OldStart < Date.Today Then
If e.OldResource <> e.NewResource Then
message = "The room cannot be changed anymore."
Else
message = "The reservation start cannot be changed anymore."
End If
ElseIf e.NewStart < Date.Today Then
message = "The reservation cannot be moved to the past."
Else
dbUpdateEvent(id_Renamed, start, [end], resource)
'message = "Reservation moved.";
End If
LoadResourcesAndEvents()
DayPilotScheduler1.UpdateWithMessage(message)
End Sub
Private Sub dbUpdateEvent(ByVal id As String, ByVal start As Date, ByVal [end] As Date, ByVal resource As String)
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString)
con.Open()
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
Dim cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource,numofday=#numofday WHERE ReservationId = #id", con)
cmd.Parameters.AddWithValue("id", id)
cmd.Parameters.AddWithValue("start", start)
cmd.Parameters.AddWithValue("end", [end])
cmd.Parameters.AddWithValue("resource", resource)
cmd.Parameters.Add("numofday", SqlDbType.Int).Value = numOfDay
cmd.ExecuteNonQuery()
End Using
End Sub
Screenshot of database table structure:
Math.floor(Math.abs(new Date(timestringone) - new Date(timestringtwo))/(1000*60*60*24))
Simply subtracting the dates returns the time in Milliseconds inbetween them. If the first time was before the second time the value is negative, so i used Math.abs to make it absolute. Then we divide trough 1000Milliseconds=1second, 60seconds=1minute, 60minutes=1hour, 24hours=1 day, and floor it to whole days. Requires two valid timestrings (timestringone and timestringtwo) to be given.
This is a javascript solution as youve included the js tag...
I am not sure about the VB.Net but you can easily accomplished it in C# using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the start and end. values for the DateTime Type and show it in a Console window, then I may write something like:
DateTime start=DateTime.MinValue;
DateTime end=DateTime.MaxValue;
TimeSpan span=end-start;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, start.ToString(), end.ToString() );
OP is having problems using the .Days property on the TimeSpan structure. I think this may help:
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
The output is:
365
Moving onto the use of your parameters, I think you would benefit from using .Add and specifying the data type:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = numOfDay
Note that you may have to change the SqlDbType. I've taken an assumption.
I would also implement Using for both the SqlConnection and SqlCommand. This for me is just good practice and the code does read better. I would also use the .Add overload for all parameters.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString),
cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource, numofday = #numofday WHERE ReservationId = #id", con)
con.Open()
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = CInt(([end] - start).TotalDays())
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
If rowsAffected = 0 Then
'nothing updated
Else
'something updated
End If
End Using

Cannot get the last row of data

In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

asp.net vb.net why is this IF not working?

I used to have this working as so....
Dim AnnEnt As Label = FormView1.FindControl("Holiday_RemainingLabel")
txtNoofDays.Text.ToString()
AnnEnt.Text.ToString()
If txtNoofDays.Text >= AnnEnt.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
I've recently change it to this and it no longer works
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
txtNoofDays.Text.ToString()
remain.Text.ToString()
If txtNoofDays.Text >= remain.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
What is the difference between the textbox in the formview and label in the formview to keep this from working?
i've since tried...
Dim days = txtNoofDays.Text
days.ToString()
AnnEnt.Text.ToString()
remain.Text.ToString()
If remain.Text.ToString < days.ToString Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
If you want to compare strings numerical, cast them to numbers.
For example(asssuming they are ints):
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
Dim remaining = Int32.Parse(remain.Text)
Dim numOfDays = Int32.Parse(txtNoofDays.Text)
If numOfDays >= remaining Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
End If
Int32.Parse Method
Otherwise you're comparing alphabetically.
String.CompareTo Method

Why no data is appearing?

I am developing an ASPX web page to return results from two SQL stored procs via VB. When I execute these two stored procs, they both return valid data. But for some reason, when I run this report it doesn't return any errors, however, it doesn't return any records/data either!
Also, I can't debug it for some reason, although I can set breakpoints! This is using VS 2008, but I think reason I can't debug is I believe this is a limited version that just works for SSRS and SSIS.
Here is an excerpt of my code:
<HTML>
<SCRIPT LANGUAGE="VB" RUNAT="Server">
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
Dim TheMonthDate As Date = DateAdd(DateInterval.Month, -1, Today)
calStartDate.SelectedDate = CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy")
calEndDate.SelectedDate = GlobalFunctions.GlobalF.MonthLastDate(CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy"))
Dim arrLevel as New ArrayList()
arrLevel.Add("All")
arrLevel.Add("Inquiries")
arrLevel.Add("All Complaints")
arrLevel.Add("Elevated Complaints")
arrLevel.Add("Non-Elevated Complaints")
dLevel.DataSource = arrLevel
dLevel.DataBind()
dLevel.selectedvalue = "All Complaints"
End If
Main
End Sub
Sub Main()
'------------------------- Query database and get arrays for the chart and bind query results to datagrid ----------------------------------------
Dim FirstMonthDate as date = calStartDate.SelectedDate
Dim LastMonthDate as date = calEndDate.SelectedDate
Dim TheLevel As Integer
Dim TitleLevel as String
Select Case dLevel.SelectedValue
Case "All"
TheLevel = 5
TitleLevel = "Inquiries and Complaints"
Case "Inquiries"
TheLevel = 0
TitleLevel = "Inquiries"
Case "All Complaints"
TheLevel = 3
TitleLevel = "All Complaints"
Case "Elevated Complaints"
TheLevel = 2
TitleLevel = "Elevated Complaints"
Case "Non-Elevated Complaints"
TheLevel = 1
TitleLevel = "Non-Elevated Complaints"
End Select
Dim DSPageData as new System.Data.DataSet
DSPageData = GlobalFunctions.GlobalF.GetComplaintTrending2(FirstMonthDate, LastMonthDate, TheLevel)
...
Dim DSDetails As New System.Data.DataSet
DSDetails = GlobalFunctions.GlobalF.GetComplaintTrendingDetails2(FirstMonthDate, LastMonthDate, TheLevel)
dgTable.DataSource = DSDetails
dgTable.DataBind()
Where in my Global.vb file I have:
'Added by Ryan on 4/17/11
Public Shared Function GetComplaintTrending2(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(2) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrending2", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
'Added by Ryan on 4/17/11
Public Shared Function GetComplaintTrendingDetails2(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(2) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrendingDetails2", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
And these stored procs are defined as:
CREATE PROCEDURE [dbo].[ComplaintTrendingDetails2]
--DECLARE
#FirstMonthDate DATETIME,
#LastMonthDate DATETIME,
#TheLevel INT
AS
SET NOCOUNT ON;
--ComplaintTrendingDetails2 '2/1/11', '2/28/11 23:59:59', 2
--SET #FirstMonthDate = '2/1/11'
--SET #LastMonthDate = '2/28/11 23:59:59'
--SET #TheLevel = '2'
SELECT DISTINCT
A.QXP_EXCEPTION_NO, A.[LEVEL], A.pRE,
A.QXP_REPORT_DATE, A.CLOSE_DATE, A.EPA_PRD_NAME,
A.EPA_PRD_CODE, A.EPL_LOT_NUMBER,
A.QXP_SHORT_DESC, A.QXP_DESCRIPTION,
A.QXP_RESOLUTION_DESC, A.CXP_CLIENT_NAME, A.Country,
C.PRODUCT, C.PRODUCT_GROUP, C.PRODUCT_ORG_UNIT,
B.DOC_DOCUMENT_NO, A.TICKET_NUM, A.CENTER_NUM,
A.COUNTRY_CODE, A.QXP_ID, B.IRF_QEI_ID
FROM ALL_COMPLAINTS A LEFT OUTER JOIN
SMARTSOLVE.V_QXP_ISSUE_REF B ON A.QXP_ID = B.IRF_QXP_ID LEFT OUTER JOIN
MANUAL.PRODUCTS C ON A.EPA_PRD_CODE = C.LIST_NUMBER
LEFT OUTER JOIN SMARTSOLVE.V_CXP_CUSTOMER_PXP D ON A.QXP_ID = D.QXP_ID
WHERE A.QXP_REPORT_DATE >= #FirstMonthDate AND A.QXP_REPORT_DATE <= #LastMonthDate
AND (A.QXP_SHORT_DESC <> 'Design Control') AND LEVEL = #TheLevel
AND (D.QXP_EXCEPTION_TYPE <> 'Non-Diagnostic' OR D.QXP_EXCEPTION_TYPE IS NULL)
ORDER BY 4
and
--ALTER PROCEDURE [dbo].[ComplaintTrending2]
DECLARE
#FirstMonthDate DATETIME,
#LastMonthDate DATETIME,
#TheLevel INT
--AS
-- SET NOCOUNT ON;
--ComplaintTrending2 '2/1/11', '2/28/11 23:59:59', 2
SET #FirstMonthDate = '2/1/11'
SET #LastMonthDate = '2/28/11 23:59:59'
SET #TheLevel = '2'
SELECT
CASE ISNULL(PRODUCT_GROUP, '') WHEN '' THEN 'Unspecified' ELSE PRODUCT_GROUP END AS PRODUCT_GROUP,
COUNT(DISTINCT A.QXP_EXCEPTION_NO) AS CountOfTickets
FROM ALL_COMPLAINTS a
LEFT OUTER JOIN MANUAL.PRODUCTS b ON a.EPA_PRD_CODE = b.LIST_NUMBER
LEFT OUTER JOIN SMARTSOLVE.V_CXP_CUSTOMER_PXP c ON a.QXP_ID = c.QXP_ID
WHERE a.QXP_REPORT_DATE >= #FirstMonthDate AND a.QXP_REPORT_DATE <= #LastMonthDate
AND (a.QXP_SHORT_DESC <> 'Design Control') AND LEVEL = #TheLevel
AND (c.QXP_EXCEPTION_TYPE <> 'Non-Diagnostic' OR c.QXP_EXCEPTION_TYPE IS NULL)
GROUP BY PRODUCT_GROUP
ORDER BY COUNT(DISTINCT a.QXP_EXCEPTION_NO) DESC
Could the problem be due to the fact that this web page uses the same SQL connection for both stored procs? The first proc should be returned initially, and the second proc after this screen. So I don't need both stored procs information simultaneously, so I would think I could reuse the same SQL connection.
OK, I found where the problem is located. If I just comment out the Level statement in the Where clause, it does return data. So only thing I changed was that one line in my SQL code and it works. This means missing data must be due to datatype incompatibility, no? What is the problem?
I think the problem is your code does not even compile. Looking at the posted page right at the start we see this:
End If
Main
End Sub
This is not valid VB. You are running an old version of your code. This is also why you can't debug it. You don't have the current one to set break points on.

Resources