SQL Syntax error, expression of non-boolean type - vb.net

This code is supposed to create a graph of revenue from money made through sales tickets at an event.
The code only executes up to da.Fill(ds) when it returns the error, which can be seen at the end of the code.
Does anybody know why
Private Sub frmRevenue_Load(sender As Object, e As EventArgs) Handles Me.Load
frmMDI.addFormToCMS()
Dim dt As DataTable
dt = New DataTable
dt.Columns.Add("Fee")
Dim sales As Integer = 0
Dim gridtable As New DataTable
gridtable.Columns.Add("Month")
gridtable.Columns.Add("Total")
gridtable.Columns.Add("#")
For i = 1 To 12
sql = "SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = " & i & " AND (YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ") AND (Status = 'SOLD' OR RESERVED" _
& " = 'AWAITING CONFIRMATION' OR Status = 'AVAILABLE' OR Status = 'AWAITING PAYMENT');"
da = New OleDb.OleDbDataAdapter(sql, con)
ds = New DataSet
da.Fill(ds)
Dim dr As DataRow
For Each dr In ds.Tables(0).Rows
monthly(i) = monthly(i) + 1
contracts = sales + 1
total(i) = total(i) + dr.Item("Fee")
yearlytotal = yearlytotal + dr.Item("Fee")
Next
Next
For i = 1 To 12
Dim month As String
Select Case i
Case 1
month = "Jan"
Case 2
month = "Feb"
Case 3
month = "Mar"
Case 4
month = "Apr"
Case 5
month = "May"
Case 6
month = "Jun"
Case 7
month = "Jul"
Case 8
month = "Aug"
Case 9
month = "Sep"
Case 10
month = "Oct"
Case 11
month = "Nov"
Case 12
month = "Dec"
Case Else
month = "ERR"
End Select
gridtable.Rows.Add(month, FormatCurrency(total(i)), monthly(i))
Next
ugTickets.DataSource = gridtable
ugTickets.DisplayLayout.Bands(0).Columns("Month").Width = 35
ugTickets.DisplayLayout.Bands(0).Columns("#").Width = 20
ugTickets.DisplayLayout.Override.AllowUpdate = DefaultableBoolean.False
txtAnnual.ReadOnly = True
txtAnnual.BackColor = Color.White
txtAnnualContracts.ReadOnly = True
txtAnnualContracts.BackColor = Color.White
chRevenue.Titles("chTitle").Text = "Predicted revenue for " & Today.Year & " - " & Year(Today.AddYears(1))
txtAnnual.Text = FormatCurrency(yearlytotal, 2)
txtAnnualContracts.Text = contracts
chRevenue.Series("Series1").Name = "Revenue"
For i = 1 To 12
chRevenue.Series("Revenue").Points.AddY(total(i))
Next
Try
chRevenue.BackColor = Color.Transparent
chRevenue.Legends("Revenue").BackColor = Color.Transparent
chRevenue.Series("Revenue").ChartArea = "ChartArea1"
chRevenue.Series("Revenue").Color = Color.SkyBlue
chRevenue.Series("Revenue").ToolTip = FormatCurrency("#VALY", 2)
Catch
End Try
End Sub
An expression of non-boolean type specified in a context where a condition is expected, near ')'.

The problem is with this bit of the SQL:
(YEAR(DatePurchased) = " & Today.Year & " OR " & Year(Today.AddYears(1)) & ")
It should probably be
(YEAR(DatePurchased) = " & Today.Year & " OR YEAR(DatePurchased) = " & Year(Today.AddYears(1)) & ")
The OR in SQL (and in most other languages) needs to have two independently valid conditions on each side. The left hand side currently looks like this:
YEAR(DatePurchased) = 2016
...which is fine. But the right looks like this:
2017
...which isn't a valid boolean.
When you get an error like this on the da.Fill() line (ie. the line that's actually running the SQL in the database), the easiest way to debug it is to print out the value of the "sql" variable.
Often, you can just look at the SQL it's generated and the problem will be obvious. Other times you have to copy it and run it directly against your database to see what the problem is.

Might be your SQL, try:
"SELECT Fee FROM tblTickets WHERE MONTH(DatePurchased) = '" & i &
"' AND (YEAR(DatePurchased) = '" & Today.Year &
"' OR '" & Year(Today.AddYears(1)) & "') " &
"AND (Status = 'SOLD' OR RESERVED = 'AWAITING CONFIRMATION' " &
"OR Status = 'AVAILABLE' " &
"OR Status = 'AWAITING PAYMENT');"

Related

vb.net implict inner join syntax error (missing operator) in query expression

This is the code where I am getting exception message. However this code worked perfect in sql server 2005 but generating error in access.
This code working fine in sql server project but in access its generating exception as I mentioned..
Public Function CalculateFeeReciept(ByVal monthid As Integer) As DataTable
Dim cmd1 As New OleDbCommand("Select * from mstFeeHead", sqlcon)
Dim dtmstFeeHead As New DataTable 'dtmstFeeHead contains all the fee heads id's
Dim adp1 As New OleDbDataAdapter(cmd1)
adp1.Fill(dtmstFeeHead)
cmd1.Dispose()
Dim selectedmonth As Integer
Dim feeheadid As Integer
Dim arr(25) As Integer 'arr contains Fee head id's that should be paid in the selected month
If monthid = 13 Then
monthid = 1
ElseIf monthid = 14 Then
monthid = 2
ElseIf monthid = 15 Then
monthid = 3
End If
selectedmonth = monthid + 3
Dim m As Integer = 0
For j As Integer = 0 To dtmstFeeHead.Rows.Count - 1
feeheadid = Convert.ToInt32(dtmstFeeHead.Rows(j)(0))
If dtmstFeeHead.Rows(j)(selectedmonth) Then
arr(m) = feeheadid
m = m + 1
End If
Next
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount " & _
"FROM " & _
"txnStudentFeeHead " & _
"INNER JOIN " & _
"mstFeeHead " & _
"ON " & _
"txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID " & _
"INNER JOIN " & _
"mstFeePlan " & _
"ON " & _
"mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID " & _
"WHERE " & _
"txnStudentFeeHead.StudentID = #StudentID) " & _
"AND " & _
"(mstFeePlan.SessionID = #SessionID) " & _
"AND " & _
"(mstFeePlan.ClassID = #ClassID) ", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()
Dim dt2 As New DataTable 'dt2 contains all the fee head id's that are alloted to the student and that should be paid in that particular month
' dt2 contains the filtrate of dt and arr
dt2 = dt.Clone()
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To dt.Rows.Count - 1
Dim dtrow As DataRow = dt2.NewRow()
If arr(i) = dt.Rows(j)(0) Then
dtrow(0) = arr(i)
dtrow(1) = dt.Rows(j)(1)
dtrow(2) = dt.Rows(j)(2)
dt2.Rows.Add(dtrow)
End If
Next
Next
cmd2 = New OleDbCommand("Select Sum(TotalFees) as TotalFees, Sum(LateFees) as TotalLateFees, Sum(OldBalance) as TotalOldBalance, Sum(Discount) as TotalDiscount, Sum(Scholarship) as TotalScholarship, Sum(Concession) as TotalConcession, Sum(AmountReceived) as TotalAmountReceived from txnFeePayment where SessionID=#SessionID and StudentID=#studentid and MonthID=#monthid Group by StudentId,MonthID", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#studentid", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = cmbSession.SelectedValue
cmd2.Parameters.Add("#monthid", OleDbType.Integer).Value = monthid
Dim dtStudentReciept As New DataTable 'dt contains all the fee head id's that are alloted to the students
adp = New OleDbDataAdapter(cmd2)
adp.Fill(dtStudentReciept)
cmd2.Dispose()
Dim dtrow1 As DataRow = dt2.NewRow()
If (dtStudentReciept.Rows.Count > 0) Then
dtrow1(0) = 0
dtrow1(1) = "Total Late Fees"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(1))
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Discount"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(3)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Scholarship"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(4)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Concession"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(5)) * -1
dt2.Rows.Add(dtrow1)
dtrow1 = dt2.NewRow()
dtrow1(0) = 0
dtrow1(1) = "Total Amount Received"
dtrow1(2) = Convert.ToInt32(dtStudentReciept.Rows(0)(6)) * -1
dt2.Rows.Add(dtrow1)
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
Else
Dim totalamount As Integer = 0
For k As Integer = 0 To dt2.Rows.Count - 1
totalamount = totalamount + dt2.Rows(k)(2)
Next
'dtrow1 = dt2.NewRow()
'dtrow1(0) = totalamount
'dtrow1(1) = "Current Month Fee"
'dtrow1(2) = totalamount
'dt2.Rows.Add(dtrow1)
End If
dgvDisplay.DataSource = dt2
For i As Integer = 0 To dgvDisplay.Columns.Count - 1
dgvDisplay.Columns.Item(i).SortMode = DataGridViewColumnSortMode.NotSortable
dgvDisplay.Columns(2).Width = 65
dgvDisplay.Columns(1).Width = 132
Next
dgvDisplay.Columns.Item(0).Visible = False
'txtTotalFees.Text = dt2.Rows(dt2.Rows.Count - 1)(0)
Return dt2
End Function
There are a couple of things wrong with your query.
You havent left any spaces once a line in code is finished and whole query may look like they are separate lines but it is a one long string without any spaces.
I have added spaces in the following piece of code at the end of each line.
("SELECT [txnStudentFeeHead].[FeeHeadID],[mstFeeHead].[FeeHeadName]," & _
"[mstFeePlan].[Amount] " & _
"FROM " & _
"[txnStudentFeeHead] " & _
"INNER JOIN " & _
"[mstFeeHead] " & _
You have put your variables in sqaure brackets [] , which means SQL Server will treat them as SQL Server Object(table name, Column Name) names and not as Variables. Remove the Square brackets.
"WHERE " & _
"([txnStudentFeeHead].[StudentID] = #StudentID) " & _
"AND" & _
"([mstFeePlan].[SessionID] = #SessionID) " & _
"AND" & _
"([mstFeePlan].[ClassID] = #ClassID) ", sqlcon)
Solved it myself by long time of effort and headache
Dim cmd2 As New OleDbCommand("SELECT txnStudentFeeHead.FeeHeadID, mstFeeHead.FeeHeadName, mstFeePlan.Amount, txnStudentFeeHead.StudentID, mstFeePlan.ClassID, mstFeePlan.SessionID FROM (txnStudentFeeHead INNER JOIN mstFeeHead ON txnStudentFeeHead.FeeHeadID = mstFeeHead.FeeHeadID) INNER JOIN mstFeePlan ON mstFeeHead.FeeHeadID = mstFeePlan.FeeHeadID WHERE (((txnStudentFeeHead.StudentID)=#StudentID) AND ((mstFeePlan.ClassID)=#ClassID) AND ((mstFeePlan.SessionID)=#SessionID))", sqlcon)
cmd2.CommandType = CommandType.Text
cmd2.Parameters.Add("#StudentID", OleDbType.Integer).Value = StudentID()
cmd2.Parameters.Add("#ClassID", OleDbType.Integer).Value = Convert.ToInt32(cmbClass.SelectedValue)
cmd2.Parameters.Add("#SessionID", OleDbType.Integer).Value = Convert.ToInt32(cmbSession.SelectedValue)
Dim dt As New DataTable 'dt contains all the fee head id's that are alloted to the students
Dim adp As New OleDbDataAdapter(cmd2)
adp.Fill(dt)
cmd2.Dispose()

vb.net - using case select query in sql for jtable

If anyone knows how to use case in query for jtable, pls take a look my code.
Dim batch_status As String = " case when status = 0 then 'Created' when status = 1 then 'Scanning' when status = 2 then 'Scan Saved' end as status"
cmd.CommandText = "SELECT * FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY " & jtSorting & " ) AS RowNum, batch_id, batch_name, date_created, profile_id, total_page, " & batch_status & ", First_ScanID, file_id " & _
" FROM [ip_ent_site].[dbo].[tbl_batch] WHERE STATUS IN (0,1,2) ) AS RowConstrainedResult " & _
" WHERE RowNum >= #jtStartIndex AND RowNum < #jtEndIndex ORDER BY RowNum ; "
if i use like this, it is working:
Dim batch_status As String = "status"
but with case, not.
whats problem here?
another part of code:
If dt.Rows.Count > 0 Then
students = (From item In dt.AsEnumerable() Select New Class1 With { _
.No = Convert.ToInt32(item(1)), _
.batch_id = Convert.ToInt64(item(2)), _
.batch_name = DirectCast(item(3), String), _
.date_created = item(4).ToString, _
.profile_id = Convert.ToInt32(item(5)), _
.total_page = Convert.ToInt32(item(6)), _
.status = Convert.ToInt32(item(7)), _
.First_ScanID = Convert.ToInt32(item(8)), _
.file_id = CheckDBNullInteger(item(9)) _
}).ToList()
End If
Use your declare statement like below.
Dim batch_status As String = " case when status = 0 then ''Created'' when status = 1 then ''Scanning'' when status = 2 then ''Scan Saved'' end as status"
may be the problem with #jtStartIndex AND #jtEndIndex.
Just found, change .status = Convert.ToInt32(item(7)) to .status = item(7).ToString,
displaying in Jtable is quite different

VB select case not working as expected

I am a total novice with visual basic and teaching myself as I go along. I am building a VB in studio 2008 (I'm obliged to use this version) that logs into a device , transmits log in and password and then transmits commands read from a .txt file using reflections. All of this is working fine. The device executes the command and outputs 1 of 28 possible responses.
I am using select case to evaluate the responses and act accordingly. The device session stops as expected when EXECUTED is seen in the session window, my test data is designed so the first response I get is "EXECUTED", the weird thing is my VB "sees" the EXECUTED message (Case 1) but select case responds as if it has seen FAILED (Case 2), subsequent lines of the test data illicit different cases (5 and 6) but the response is always the next case along. I have tried Case n, case is = n, case "string value" but I get errors.
Here's my code - note that I haven't defined all 28 cases yet but the undefined ones are REM'ed out in my active version. Any ideas or suggestions would be gratefully received!
Option Explicit On
Public Class modCaseSelect
Shared Sub Dev_Responses(ByVal refl)
Dim Result As String
Dim CR = vbCr
Dim Resp As Integer
Dim Dev_Resp(28) As String
Dev_Resp(0) = "RUNNING"
Dev_Resp(1) = "EXECUTED"
Dev_Resp(2) = "FAILED"
Dev_Resp(3) = "SEMANTICS ERROR"
Dev_Resp(4) = "NONEXISTENT"
Dev_Resp(5) = "NOT FOUND"
Dev_Resp(6) = "SPECIAL"
Dev_Resp(7) = "CONFIRM: Y/N"
Dev_Resp(8) = "CONFIRM (Y/N)"
Dev_Resp(9) = "CONFIRM EXECUTION: Y/N"
Dev_Resp(10) = "ALREADY EXECUTED"
Dev_Resp(11) = ""
Dev_Resp(12) = ""
Dev_Resp(13) = ""
Dev_Resp(14) = ""
Dev_Resp(15) = ""
Dev_Resp(16) = ""
Dev_Resp(17) = ""
Dev_Resp(18) = ""
Dev_Resp(19) = ""
Dev_Resp(20) = ""
Dev_Resp(21) = ""
Dev_Resp(23) = ""
Dev_Resp(23) = ""
Dev_Resp(24) = ""
Dev_Resp(25) = ""
Dev_Resp(26) = ""
Dev_Resp(27) = ""
Dev_Resp(28) = "IN PROGRESS"
With refl
Select Case .WaitForStrings(Dev_Resp, "0:4:30") 'checkDev_Resp
Case 0 ' "RUNNING"
Result = Dev_Resp(0)
Resp = MsgBox((Dev_Resp(0) & CR & CR & Continue?"), 17, "Case 0 error")
Case 1 ' "EXECUTED"
Result = Dev_Resp(1)
Resp = MsgBox((Dev_Resp(1) & CR & CR & "Continue?"), 17, "Case 1")
Case 2 ' "FAILED"
Result = Dev_Resp(2)
Resp = MsgBox((Dev_Resp(2) & CR & CR & "Continue?"), 17, "Case 2 error")
Case 3 ' "SEMANTICS ERROR"
Result = Dev_Resp(3)
Resp = MsgBox((Dev_Resp(3) & CR & CR & "Continue?"), 17, "Case 3 error")
Case 4 ' "NONEXISTENT"
Result = Dev_Resp(4)
Resp = MsgBox((Dev_Resp(4) & CR & CR & "Continue?"), 17, "Case 4 error")
Case 5 ' "NOT FOUND"
Result = Dev_Resp(5)
Resp = MsgBox((Dev_Resp(5) & CR & CR & "Continue?"), 17, "Case 5 error")
Case 6 ' "SPECIAL"
Result = Dev_Resp(6)
Resp = MsgBox((Dev_Resp(6) & CR & CR & "Continue?"), 17, "Case 6 error")
Case 7 ' "CONFIRM: Y/N"
Result = Dev_Resp(7)
.Transmit("Y" & CR)
Case 8 ' "CONFIRM (Y/N)"
Result = Dev_Resp(8)
.Transmit("Y" & CR)
Case 9 ' "CONFIRM EXECUTION: Y/N"
Result = Dev_Resp(9)
.Transmit("Y" & CR)
Case 10 ' "ALREADY EXECUTED"
Result = Dev_Resp(10)
Resp = MsgBox((Dev_Resp(10) & CR & CR & "Continue?"), 17, "Case 10 error")
Case 11 ' ""
Result = Dev_Resp(11)
Case 12 ' ""
Result = Dev_Resp(12)
Case 13 ' ""
Result = Dev_Resp(13)
Case 14 ' ""
Result = Dev_Resp(14)
Case 15 ' ""
Result = Dev_Resp(15)
Case 16 ' ""
Result = Dev_Resp(16)
Case 17 ' ""
Result = Dev_Resp(17)
Case 18 ' ""
Result = Dev_Resp(18)
Case 19 ' ""
Result = Dev_Resp(19)
Case 20 ' ""
Result = Dev_Resp(20)
Case 21 ' ""
Result = Dev_Resp(21)
Case 22 ' ""
Result = Dev_Resp(22)
Case 23 ' ""
Result = Dev_Resp(23)
Case 24 ' ""
Result = Dev_Resp(24)
Case 25 ' ""
Result = Dev_Resp(25)
Case 26 ' ""
Result = Dev_Resp(26)
Case 27 ' ""
Result = Dev_Resp(27)
Case 28 ' "IN PROGRESS"
Result = Dev_Resp(28)
Resp = MsgBox((Dev_Resp(28) & CR & CR & "Continue?"), 17, "Case 28 error")
Case Else
End Select
End With
End Sub
End Class
You are missing a double quote " in your first Case. Try changing it to this:
Case 0 ' "RUNNING"
Result = Dev_Resp(0)
Resp = MsgBox((Dev_Resp(0) & CR & CR & "Continue?"), 17, "Case 0 error")
Notice I've added the double quote before "Continue?".
Get rid of the With statement. Create and assign a holder variable and use that with the select statement. Doing so will allow you to see what is actually getting passed into the select statement by setting a stop point in the debugger.
Dim temp_resp as integer = refl.WaitForStrings(Dev_Resp, "0:4:30")
Select Case temp_resp
'the case statements here.
End Select
Reflections WaitForStrings uses a zero-based array parameter, but it returns a 1-based index of strings. Waitforstrings sees array entry zero as the first valid entry so the first select case (Case = 1) corresponds to array entry 0.

How to merge cells and remove blank spaces in my DataGrid using proper loop

My title is still broad so i'll explain here further.
This is my current output using my code:
.
But I want to make it look like this..
As you can see on the pictures, i want to remove the blank spaces. Because if I selected MORE data, let's say I selected 7 more days, it will go DIAGONALLY not horizontally.
I think I have a problem regarding my loops. Hope you can help me trace because I've been stuck here for a week debugging. (nevermind my long query, i just want to post all my code. I've also added comments for easier debugging.)
Here's my code:
Private Sub LoadDateAndUser()
Dim SqlStr As String = ""
Dim sqlConn As New SqlConnection(DataSource.ConnectionString)
Dim sqlComm As New SqlCommand(SqlStr, sqlConn)
Dim sqlAdapter As New SqlDataAdapter(sqlComm)
Dim o_Dataset As New DataSet()
SqlStr = " SELECT convert(varchar(10), A.TransDate, 101) as TransDate,ADMMED.TransNum, ADMMED.AdministeredDate, D.Dosage [Dosage], ISNULL(C.GenericName, ' ') + ' (' + IsNull(B.ItemName,'') + ' ' + IsNull(B.ItemDesc,'') + ')' [Medication], ADMMED.UserID" & _
" FROM INVENTORY..tbInvStockCard as A" & _
" LEFT OUTER JOIN INVENTORY..tbInvMaster as B On A.ItemID = B.ItemID " & _
" LEFT OUTER JOIN Inventory.dbo.tbForGeneric as C On B.GenericID = C.GenericID" & _
" LEFT OUTER JOIN Station..tbNurse_AdministeredMedicines ADMMED on a.idnum= ADMMED.idnum " & _
" LEFT OUTER JOIN build_file.dbo.tbCoDosage as D on A.DosageID = D.DosageID" & _
" LEFT OUTER JOIN Station.dbo.tbNurseCommunicationFile as E on A.IdNum = E.IDnum and E.ReferenceNum = A.RefNum" & _
" WHERE A.IdNum = '" & Session.Item("IDNum") & "' and ( A.RevenueID = 'PH' or A.RevenueID = 'PC' ) " & _
" AND A.LocationID = '20' and Not IsNull(ADMMED.AdministeredDate, '') = ''" & _
" AND A.RefNum = ADMMED.ReferenceNum and ADMMED.ItemID = A.itemid" & _
" AND (B.ItemClassificationID = '1' or B.ItemClassificationID = '10' or B.ItemClassificationID = '11' or B.ItemClassificationID = '16' or B.ItemClassificationID = '2' or B.ItemClassificationID = '9')" & _
" order by TransDate desc,ADMMED.AdministeredDate desc"
sqlComm.CommandText = SqlStr
sqlAdapter.Fill(o_Dataset, "Table")
Dim o_Row As DataRow
Dim o_AdmDates As New Collection()
Dim s_FormattedLastAdmDate As String = ""
Dim s_FormattedAdmDate As String = ""
Dim o_DerivedTable As New DataTable()
With o_DerivedTable
.Columns.Add("TransDate")
.Columns.Add("Medication")
.Columns.Add("Dosage")
.Columns.Add("TransNum")
End With
'Select all unformatted administered dates from the query
Dim o_UnformattedAdmDates As DataRow() = o_Dataset.Tables(0).Select("", "AdministeredDate Desc")
'Extract distinct administered dates and change its format
For Each o_Row In o_UnformattedAdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format) 'eg. Jan 01 15
If s_FormattedLastAdmDate <> s_FormattedAdmDate Then
s_FormattedLastAdmDate = s_FormattedAdmDate
o_AdmDates.Add(s_FormattedLastAdmDate) 'add all formatted dates in o_AdmDates
End If
Next
'Add formatted administred dates to derived table
Dim o_Item As String
For Each o_Item In o_AdmDates
o_DerivedTable.Columns.Add(o_Item)
Next
'Loop through the administred date
Dim o_NewRow As DataRow
Dim o_NextRow As DataRow
Dim i_Ctr As Integer
Dim x_isNewRow As Boolean = True
Dim i_MaxRec As Integer
i_MaxRec = o_Dataset.Tables(0).Rows.Count - 1
For i_Ctr = 0 To i_MaxRec
o_Row = o_Dataset.Tables(0).Rows(i_Ctr)
If i_Ctr <> i_MaxRec Then
o_NextRow = o_Dataset.Tables(0).Rows(i_Ctr + 1)
End If
If x_isNewRow Then
o_NewRow = o_DerivedTable.NewRow()
End If
o_NewRow("TransDate") = o_Row("TransDate")
o_NewRow("Medication") = o_Row("Medication")
o_NewRow("Dosage") = o_Row("Dosage")
o_NewRow("TransNum") = o_Row("TransNum")
'Fill approriate result date column based on query
For Each o_Item In o_AdmDates
s_FormattedAdmDate = Format(CDate(o_Row.Item("AdministeredDate")), KC_Date_Format)
Dim AdmTim As DateTime = DateTime.Parse(o_Row("AdministeredDate"))
If s_FormattedAdmDate = o_Item Then
o_NewRow(s_FormattedAdmDate) = AdmTim.ToString("hh:mm tt") + " - " + o_Row("UserID")
End If
Next
If i_Ctr < i_MaxRec _
And Not o_NextRow Is Nothing _
And o_Row("TransDate") = o_NextRow("TransDate") _
And o_Row("Medication") = o_NextRow("Medication") _
And o_Row("Dosage") = o_NextRow("Dosage") _
And o_Row("AdministeredDate") = o_NextRow("AdministeredDate") Then
x_isNewRow = False
Else
o_DerivedTable.Rows.Add(o_NewRow)
x_isNewRow = True
End If
Next
'Bind derived table
dgSheet.DataSource = o_DerivedTable
dgSheet.DataBind()
If o_Dataset.Tables(0).Rows.Count > 0 Then
GroupGridView(dgSheet.Items, 0, 3)
Else
End If
End Sub
I think you must review your programming logic:
After that huge ugly SqlStr : you will have a DataSet, with a Table with all rows mixed !?
Let's try a pseudo-code:
I think is better to create in that DataSet, 2 Tables:<br>
**first** table with: id, DateOrder, Medication, Dosage <br>
and **second** table with: idDate, FirstTable.id, AdministeredDate
after that you know how many ADMMED.AdministeredDate.Count are, because you must know how manny columns you need to add
create a 3-rd table from iteration of first table, nested with second by ID.
Set as Datasource for DataGridView the Third DataTable.
So you have 2 datasets, and generate this one .. one to many ..
.. I have no time now, if you don't get the ideea .. forget it !

commandtext property has not been initialized vb.net

I am new to vb.net and tried to execute the code its working fine but when I am scheduling the code in another server in network by running the exe file only, then I am getting the error as:
"commandtext property has not been initialized"
Sub send_SMS()
Console.WriteLine("Begining of the send_SMS() ")
Dim dt As New DataTable
Dim st1, sql As String
Dim fetcheduser, fetchedpno As String
Dim J As Integer
J = Now.Hour
Console.WriteLine("J Now.Hour =: " + J.ToString)
'A shift
If J >= 14 And J < 22 Then
sql = " SELECT * FROM YKPI_VALUE "
sql = sql & " WHERE KPV_USER_ID='QEXP' "
sql = sql & " AND KPV_TYP_ID='A' "
sql = sql & " AND KPV_FROM_DATE=TO_CHAR(SYSDATE,'YYYYMMDD') "
Console.WriteLine("J = 14 ")
st.Text = "A"
End If
'B Shift
If J >= 22 And J < 6 Then
sql = " SELECT * FROM YKPI_VALUE "
sql = sql & " WHERE KPV_USER_ID='QEXP' "
sql = sql & " AND KPV_TYP_ID='B' "
sql = sql & " AND KPV_FROM_DATE=TO_CHAR(SYSDATE,'YYYYMMDD') "
Console.WriteLine("J = 22 ")
st.Text = "B"
End If
'C Shift
If J >= 6 And J < 14 Then
sql = " SELECT * FROM YKPI_VALUE "
sql = sql & " WHERE KPV_USER_ID='QEXP' "
sql = sql & " AND KPV_TYP_ID='C' "
sql = sql & " AND KPV_FROM_DATE=TO_CHAR(SYSDATE-1,'YYYYMMDD') "
Console.WriteLine("J = 6 ")
st.Text = "C"
DAT = DAT.AddDays(-1)
End If
Dim DA As New OracleDataAdapter(sql, oraconn)
DA.Fill(dt)
Console.WriteLine("Before dt.Rows count ")
Dim MaxRows, MaxColums, inc As Integer
MaxRows = dt.Rows.Count
MaxColums = dt.Columns.Count
Dim multiarray(,) As String = New String(MaxRows, MaxColums) {}
Console.WriteLine("Value of MaxRows = " + MaxRows.ToString)
Console.WriteLine("Value of MaxColums = " + MaxColums.ToString)
If (inc <> MaxRows) Then
'inc = inc + 1
Console.WriteLine("Inside dt.Rows and Before for loop ")
For inc = 0 To MaxRows - 1
'For col = 0 To MaxColums
dt.Rows(inc).Item(10) = dt.Rows(inc).Item(10).ToString.Replace("Q", "")
multiarray(inc, 1) = dt.Rows(inc).Item(2).ToString()
multiarray(inc, 2) = dt.Rows(inc).Item(4).ToString()
multiarray(inc, 3) = dt.Rows(inc).Item(10).ToString()
Next
End If
Dim queryusr As String
queryusr = ""
Dim sql_CMD_TD As New OracleCommand(sql, oraconn)
If Not oraconn.State = ConnectionState.Open Then
oraconn.Open()
End If
Dim doNotSendSMS = False
Dim sqldr As OracleDataReader = sql_CMD_TD.ExecuteReader()
If sqldr.HasRows Then
oraconn.Close()
queryusr = " SELECT TSU_USER,TSU_USERNAME FROM T_SDM_USERS "
queryusr = queryusr & "WHERE TSU_SCREENID='QESMS'AND TSU_VALIDITY='Y' "
dt = New DataTable
DA = New OracleDataAdapter(queryusr, oraconn)
DA.Fill(dt)
If Not doNotSendSMS Then
Dim ora_CMD_SMS As New OracleCommand(queryusr, oraconn)
If oraconn.State = ConnectionState.Closed Then
oraconn.Open()
End If
st1 = st.Text
Dim ORA_DR As OracleDataReader = ora_CMD_SMS.ExecuteReader()
If ORA_DR.HasRows Then
While ORA_DR.Read()
fetcheduser = ORA_DR("TSU_USERNAME")
fetchedpno = ORA_DR("TSU_USER")
Console.WriteLine("Before insertIntoSMS function call ")
Console.WriteLine(" Value of st1 :" + st1.ToString)
insertIntoSMS_hbf(fetcheduser, fetchedpno, st1, multiarray, MaxRows, MaxColums)
Console.WriteLine("Outside of insertIntoSMS function call ")
End While
ORA_DR.Close()
End If
If oraconn.State = ConnectionState.Open Then
oraconn.Close()
End If
End If
End If
End Sub