commandtext property has not been initialized vb.net - 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

Related

How to speed up pie charts creation in VB Web?

I have a web page that can create multiple pie charts based on an SQL query that executes when the page is loading. However I have noticed that the page loading takes too long (around 30 seconds). I checked the SQL formula and can confirm that it is working fine (results given almost instantly).
There are 40 different pie charts the page needs to create, and the page also have the option to generate a single pie chart and that works fast enough.
So I can deduce that it's the pie chart generation that is slow when it needs to create 40 of them. Is there a way to help speed up the pie chart creation process?
Here is my code for reference.
Sub draw_chart1() 'All Machines
Dim check1, check2, fi, cnt
Dim sql
Dim myConnectionString As String = "Provider=SQLOLEDB;" & SQLDB_pp.ConnectionString
fi = 0
cnt = 0
PlaceHolder1.Dispose()
PlaceHolder2.Dispose()
'Get all model
Dim query1 As String = String.Format("SELECT DISTINCT A.MacID FROM dbo.tblMachine A LEFT JOIN dbo.tblDataHdr b on a.MacID = b.MacID where DayID between '" & TextBox1.Text & "' AND '" & TextBox3.Text & "' ORDER BY A.MACID")
Dim dt1 As DataTable = GetData(query1)
For Q As Integer = 0 To dt1.Rows.Count - 1
'For Q As Integer = 0 To 1
check1 = dt1.Rows(Q)(0).ToString()
'This is the slow query
Dim query As String = String.Format("SELECT Z.MacID, Z.EventName, ISNULL(DIFF,0) AS DIFF FROM (select distinct MacID, EventName from dbo.tblMachine a join (SELECT DISTINCT EVENTNAME FROM dbo.tblEvtDur where EventName <> 'ON' ) b on b.EventName <> '' and MacID in ('" & check1 & "') ) Z LEFT JOIN (SELECT A.MacID, A.EventName, SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) as diff,round(SUM(DATEDIFF(SECOND, A.STARTdt, A.eNDdt)) / cast(aVG(Tdiff) as decimal(30,8)),4) * 100 AS PER FROM dbo.tblEvtDur A LEFT JOIN ( SELECT MacID, SUM(DATEDIFF(SECOND, STARTdt, eNDdt)) as Tdiff FROM dbo.tblEvtDur WHERE DayID between '" & TextBox1.Text & "' and '" & TextBox3.Text & "' GROUP BY MacID ) B ON A.MacID = B.MacID WHERE DayID between '" & TextBox1.Text & "' and '" & TextBox3.Text & "' AND A.MacID in ('" & check1 & "') group by A.MacID, A.EventName) a ON A.EVENTNAME = Z.EVENTNAME and Z.MacID = a.MacID order by Z.MacID, Z.EventName")
Dim mychart As Chart = New Chart
' Dim myplace As PlaceHolder = New PlaceHolder
Dim ChartArea1 As ChartArea = New ChartArea
Dim Legend1 As Legend = New Legend
Dim dt As DataTable = GetData(query)
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As Integer() = New Integer(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(1).ToString()
' y(i) = dt.Rows(i)(2).ToString()
y(i) = Convert.ToInt32(dt.Rows(i)(2))
Next
'Dim myConnection As New OleDbConnection(myConnectionString)
'Dim myCommand As New OleDbCommand(sql, myConnection)
'mychart.Width = Unit.Pixel(Session("sw") - 100)
'mychart.Height = Unit.Pixel((Session("sh") / 2) - 88)
mychart.Width = 600
mychart.Height = 400
mychart.ChartAreas.Clear()
mychart.ChartAreas.Add("ChartArea1")
mychart.Series.Clear()
mychart.Series.Add(0)
mychart.Series(0).Points.DataBindXY(x, y)
mychart.Titles.Clear()
mychart.Titles.Add("[" & Q + 1 & "] " & check1.ToString.ToUpper)
mychart.Titles(0).Font = New System.Drawing.Font("Tahoma", 12, System.Drawing.FontStyle.Bold)
mychart.Titles(0).BackColor = Color.PaleTurquoise
mychart.Titles(0).ForeColor = Color.Black
mychart.Series(0).ChartType = SeriesChartType.Pie
' mychart.Series(0).Points.DataBindXY(x, y)
mychart.Series(0).LegendText = "#VALX"
mychart.Series(0)("BarLabelStyle") = "Center"
mychart.Series(0)("pointWidth") = "1"
mychart.Series(0).BorderDashStyle = ChartDashStyle.Solid
mychart.Series(0).BorderWidth = 2
mychart.Series(0).Label = "#PERCENT"
mychart.Series(0).ShadowColor = Color.Gray
mychart.Series(0).ShadowOffset = 10
mychart.Series(0).LabelBackColor = Drawing.Color.Cornsilk
mychart.Series(0).Font = New Font("Tahoma", 9, FontStyle.Bold)
'Chart1.Series(0).LabelToolTip = "#LABEL Percent: #PERCENT"
mychart.Series(0).LegendToolTip = "#VALX - #PERCENT"
mychart.Series(0).ToolTip = "#VALX - #PERCENT"
mychart.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
mychart.Series(0).CustomProperties = "DrawingStyle=LightToDark"
'new
Chart1.Series(0).CustomProperties = "PieLabelStyle=Outside"
mychart.ChartAreas("ChartArea1").BorderDashStyle = BorderStyle.Solid
mychart.Palette = ChartColorPalette.None
mychart.Series(0).BorderDashStyle = ChartDashStyle.Solid
mychart.Series(0).BorderWidth = 2
mychart.Series(0).BorderColor = Color.Black
mychart.PaletteCustomColors = {Drawing.Color.Black, Drawing.Color.LightGray, Drawing.Color.Blue, Drawing.Color.Yellow, Drawing.Color.Red, Drawing.Color.Orange, Drawing.Color.Green}
mychart.Legends.Clear()
mychart.Legends.Add(0)
'Chart1.Legends(0).Enabled = True
''Chart1.Legends(0).BackColor = Drawing.Color.LightGreenplace
mychart.Legends(0).Font = New Font("Tahoma", 10, FontStyle.Bold)
mychart.Legends(0).Docking = System.Web.UI.DataVisualization.Charting.Docking.Bottom
'Chart1.Legends(0).Alignment = Drawing.StringAlignment.Center
'Chart1.Legends(0).BackColor = System.Drawing.Color.Transparent
mychart.DataBind()
'myplace.Visible = True
If (Q + 1) Mod 2 <> 0 Then
PlaceHolder1.Controls.Add(mychart)
' Dim spacer As LiteralControl = New LiteralControl("<p />")
' PlaceHolder1.Controls.Add(spacer)
End If
'Exit For
If (Q + 1) Mod 2 = 0 Then
PlaceHolder2.Controls.Add(mychart)
'Dim spacer As LiteralControl = New LiteralControl("<p />")
' PlaceHolder2.Controls.Add(spacer)
End If
Next
End Sub

Program not responding fast enough

To get started I created a program at work to read our network tools and store the retrieved data to our database. No problem but the way I set it up originally was every tool had its own instance and was hard coded for each tool.
Now I was tasked with making the program more user friendly so I can send it to other places. So now I database the IP address of tool and location on assembly line so I can cross reference while the code is executing.
On the new program I created an array of my Tool Reader class:
Dim TB(50) As ReadAtlascopco
Then I run through this loop on form load:
Private dict As New Dictionary(Of Timer, Label)()
Private Sub CreateTimers()
For i = 0 To IPCount
TB(i) = New ReadAtlascopco
' timer(i) = New Timerarray
Next
For i As Integer = 1 To IPCount
C = i - 1
timer = New Timer() With {.Interval = 250, .Enabled = True, .Tag = i.ToString}
AddHandler timer.Tick, (AddressOf timer_Tick)
' timer.Interval = (100 * i)
label = New Label()
label.Name = "label" & i
label.Location = New Point(10, 10 + i * 25)
label.Font = New Font("Sans Serif", 9, FontStyle.Bold)
label.AutoSize = True
'label.Width = 100
'label.AutoEllipsis = False
label.TabIndex = i
label.Visible = True
Me.Controls.Add(label)
dict(timer) = label
TB(C).ipaddress = TBData(C)
TB(C).StartConnection()
timer.Enabled = True
timer.Start()
Next
Then I go through the timer tick event. Everything works great up until this point. Once I go through the tick event it starts lagging and I miss data.
Is there a way to speed this process up?
Here is the tick event:
Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim Stop_Num(50) As String
Dim Line_Name(50) As String
Dim t As Timer = DirectCast(sender, Timer)
Dim s As Integer = Val(t.Tag) - 1
Param1 = TBData(s)
CWE(s) = False
If Activestat(s) = True Then
Dim SQL1 As String = "SELECT Stop_Num FROM TBL_Added_Boxes Where(IP_Address = N'" + Param1 + "')"
Dim output1 As String
Using cn = New SqlConnection(My.Settings.Torque_InfoConnectionString)
Using cmd = New SqlCommand(SQL1, cn)
cn.Open()
Try
Dim dr1 = cmd.ExecuteReader()
While dr1.Read()
output1 = dr1("Stop_Num").ToString()
End While
Catch ex As SqlException
WriteToErrorLog("Error pulling data from the database in reguards to torque box info (Stop Number).", ex.ToString(), "Failed to retreive Torque controler Info .")
End Try
cn.Close()
End Using
End Using
Stop_Num(0) = output1
Dim SQL2 As String = "SELECT Line_On FROM TBL_Added_Boxes Where(IP_Address = N'" + Param1 + "')"
Dim output2 As String
Using cn = New SqlConnection(My.Settings.Torque_InfoConnectionString)
Using cmd = New SqlCommand(SQL2, cn)
cn.Open()
Try
Dim dr2 = cmd.ExecuteReader()
While dr2.Read()
output2 = dr2("Line_On").ToString()
End While
Catch ex As SqlException
WriteToErrorLog("Error pulling data from the database in reguards to torque box info (Line On).", ex.ToString(), "Failed to retreive Torque controler Info .")
End Try
cn.Close()
End Using
End Using
Line_Name(0) = output2
If Line_Name(0) = "Line 1" Then
Newlinename(s) = "Line1Serial"
ElseIf Line_Name(0) = "Line 2" Then
Newlinename(s) = "Line2Serial"
ElseIf Line_Name(0) = "Line 3" Then
Newlinename(s) = "Line3Serial"
End If
Param3 = Stop_Num(0)
Param2 = Newlinename(s)
Dim SQL As String = "SELECT " + Newlinename(s) + " FROM TBL_RunningLineStatus Where(Stop_Number = N'" + Stop_Num(0) + "')"
Dim output As String
Using cn = New SqlConnection(My.Settings.ScanBypassConnectionString)
Using cmd = New SqlCommand(SQL, cn)
cn.Open()
Try
Dim dr = cmd.ExecuteReader()
While dr.Read()
output = dr(Param2).ToString()
End While
Catch ex As SqlException
WriteToErrorLog("Error Pulling Data From The Database In reguards to Seat Data.", ex.ToString(), "Failed to retreive buildline data.")
End Try
cn.Close()
End Using
End Using
TBSData(s) = output
If Killall = "True" Then
t.Stop()
Else
Try
TB(s).GetData()
If TB(s).Colorselect = 0 Then
dict(t).BackColor = System.Drawing.Color.GreenYellow
dict(t).ForeColor = Color.Black
ElseIf TB(s).Colorselect = 1 Then
TB(s).ipaddress = TBData(s)
TB(s).StartConnection()
dict(t).BackColor = System.Drawing.Color.Red
dict(t).ForeColor = Color.White
ElseIf TB(s).Colorselect = 2 Then
dict(t).BackColor = System.Drawing.Color.Purple
dict(t).ForeColor = Color.White
End If
If Olddata(s) <> TB(s).TorboxData(20) Then
Cname(s) = TB(s).TorboxData(2)
Tstatus(s) = TB(s).TorboxData(7)
TValue(s) = TB(s).TorboxData(19)
Sdata(s) = TBSData(s)
Tfinal(s) = TB(s).TorboxData(18)
TPset(s) = TB(s).TorboxData(30)
TFinalAngle(s) = TB(s).TorboxData(24)
RDAmin(s) = TB(s).TorboxData(25)
RDAmax(s) = TB(s).TorboxData(26)
RDAactual(s) = TB(s).TorboxData(27)
RDAStat(s) = TB(s).TorboxData(15)
Anglemin(s) = TB(s).TorboxData(21)
Anglemax(s) = TB(s).TorboxData(22)
AngleFT(s) = TB(s).TorboxData(23)
Anglestat(s) = TB(s).TorboxData(13)
Tormin(s) = TB(s).TorboxData(16)
Tormax(s) = TB(s).TorboxData(17)
TTTights(s) = TB(s).TorboxData(28)
TTSerial(s) = TB(s).TorboxData(29)
Olddata(s) = TB(s).TorboxData(20)
CWE(s) = True
dict(t).Text = t.Tag + " ) " + "Controler Name : " + TB(s).TorboxData(2) + ": Status : " + TB(s).Connectiontext + " : Date : " + Now() + " :: SERIAL # : " + Sdata(s) + " : From : " + Newlinename(s) + " :: Stop : " + Param3 + ""
' .Text = t.Tag + " ) " + "Controler Name : " + TB(s).TorboxData(2) + ": Status : " + TB(s).Connectiontext + " : Date : " + Now() + " :: SERIAL # : " + Sdata(s) + " : From : " + Newlinename(s) + " :: Stop : " + Param3 + "")
dict(t).BackColor = System.Drawing.Color.Yellow
Else
If TB(s).networkconnected = True Then
dict(t).AutoSize = True
'dict(t).Text = "Controler Name : " + TB(s).TorboxData(2) + ": Status : " + TB(s).Connectiontext + " : Date : " + Now()
dict(t).BackColor = System.Drawing.Color.Yellow
dict(t).ForeColor = Color.Black
Else
dict(t).Text = TB(s).Connectiontext + " :::: " + Now() + " :: " + TBData(s)
dict(t).BackColor = System.Drawing.Color.Red
dict(t).ForeColor = Color.White
End If
End If
Catch ex As Exception
WriteToErrorLog("Error Reading the torque box .", ex.Message, "Failed read torque data.")
Finally
'If CWE(s) = True Then
' Call Data_Entry()
'End If
If TValue(s) <> "" And CWE(s) = True Then
Try
con.ConnectionString = My.Settings.ScanBypassConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO TBL_Torque_Value1 (Serial_Num, Controler_Name, Torque_Status, Torque_Value, Date_Time,Extra_1, Extra_2, Extra_3,RundownMin,RundownMax,RundownAct,RundownStat,AngleMin,AngleMax,AngleFT,AngleStat,TorqueMin,TorqueMax,ToolTightens,Toolserialnum) VALUES(#p1,#p2, #p3, #p4, #p5, #p6, #p7, #p8,#p9, #p10, #p11, #p12, #p13, #p14, #p15, #p16, #p17, #p18, #p19, #p20)"
cmd.Parameters.Add("#p1", SqlDbType.NVarChar, 50)
cmd.Parameters.Add("#p2", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p3", SqlDbType.NVarChar, 50)
cmd.Parameters.Add("#p4", SqlDbType.NVarChar, 50)
cmd.Parameters.Add("#p5", SqlDbType.DateTime2, 7)
cmd.Parameters.Add("#p6", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p7", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p8", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p9", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p10", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p11", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p12", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p13", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p14", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p15", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p16", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p17", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p18", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p19", SqlDbType.NVarChar, 250)
cmd.Parameters.Add("#p20", SqlDbType.NVarChar, 250)
cmd.Parameters("#p1").Value = Sdata(s)
cmd.Parameters("#p2").Value = Cname(s)
cmd.Parameters("#p3").Value = Tstatus(s)
cmd.Parameters("#p4").Value = TValue(s)
cmd.Parameters("#p5").Value = Now()
cmd.Parameters("#p6").Value = Tfinal(s)
cmd.Parameters("#p7").Value = TFinalAngle(s) + " Deg"
cmd.Parameters("#p8").Value = "P:" + TPset(s)
cmd.Parameters("#p9").Value = RDAmin(s)
cmd.Parameters("#p10").Value = RDAmax(s)
cmd.Parameters("#p11").Value = RDAactual(s)
cmd.Parameters("#p12").Value = RDAStat(s)
cmd.Parameters("#p13").Value = Anglemin(s)
cmd.Parameters("#p14").Value = Anglemax(s)
cmd.Parameters("#p15").Value = AngleFT(s)
cmd.Parameters("#p16").Value = Anglestat(s)
cmd.Parameters("#p17").Value = Tormin(s)
cmd.Parameters("#p18").Value = Tormax(s)
cmd.Parameters("#p19").Value = TTTights(s)
cmd.Parameters("#p20").Value = TTSerial(s)
cmd.ExecuteNonQuery()
Catch ex As Exception
WriteToErrorLog("Error Inserting Data into The Database In reguards to Torque Data.", ex.Message, "Failed to Insert Torque Data.")
con.Close()
cmd.Parameters.Clear()
Cname(s) = ""
Tstatus(s) = ""
TValue(s) = ""
Sdata(s) = ""
Tfinal(s) = ""
TFinalAngle(s) = ""
TPset(s) = ""
RDAmin(s) = ""
RDAmax(s) = ""
RDAactual(s) = ""
RDAStat(s) = ""
Anglemin(s) = ""
Anglemax(s) = ""
AngleFT(s) = ""
Anglestat(s) = ""
Tormin(s) = ""
Tormax(s) = ""
TTTights(s) = ""
TTSerial(s) = ""
Finally
con.Close()
cmd.Parameters.Clear()
Cname(s) = ""
Tstatus(s) = ""
TValue(s) = ""
Sdata(s) = ""
Tfinal(s) = ""
TFinalAngle(s) = ""
TPset(s) = ""
RDAmin(s) = ""
RDAmax(s) = ""
RDAactual(s) = ""
RDAStat(s) = ""
Anglemin(s) = ""
Anglemax(s) = ""
AngleFT(s) = ""
Anglestat(s) = ""
Tormin(s) = ""
Tormax(s) = ""
TTTights(s) = ""
TTSerial(s) = ""
End Try
End If
End Try
End If
Else
dict(t).AutoSize = True
dict(t).Text = "Torque Box is not active :: " + TBData(s) + " ::"
dict(t).BackColor = System.Drawing.Color.Black
dict(t).ForeColor = Color.White
End If
End Sub
The class that is being referenced is one that I created and is working but like I said everything is slow. It seems to hang for 3 to 5 seconds in a single tick event.
As of now I only have 21 tools setup and it will take about 15 to 30 seconds to cycle through all.

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()

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 !

Automatic chart update with new data entry

My chart loads data from a DataGridView.
I want to automatically update my chart with new data if new values are inserted into the DataGridView.
My chart is bound to table1 and table2 in my DataGridView which gets values from a DataTable. Here is a small portion of the code:
Dim myData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(myData)
-
Chart1.DataSource = myData
Chart1.Series("Series1").ValueMemberX = "table1"
Chart1.Series("Series1").ValueMembersY = "table2"
Here is the complete code:
Try
wcconn.Open()
Dim wcCommand As New MySqlCommand()
''telesales name
' Dim wcQuery = "SELECT ID, Telesales, SUBSTRING(lastupdatedate, 1, 10) as 'Day', SUBSTRING(lastupdatetime FROM -9 FOR 6) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & newDate & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
' wcCommand.Connection = wcconn
' wcCommand.CommandText = wcQuery
Dim newDate As String
newDate = dateWorkCheck.Text
newDate = newDate.Replace("/", "-")
Dim y, m, d As String
y = newDate.Substring(6, 4)
m = newDate.Substring(3, 2)
d = newDate.Substring(0, 2)
newDate = y & "-" & m & "-" & d
Dim wcQuery = "SELECT ID, Telesales, lastupdatedate as 'Day', SUBSTRING(lastupdatetime FROM -8 FOR 2) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & newDate & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
wcCommand.Connection = wcconn
wcCommand.CommandText = wcQuery
Dim wcData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(wcData)
Dim i = 0
If wcData.Rows.Count = 0 Then
wcAdapter.Dispose()
Try
Dim wQuery = "SELECT ID, Telesales, lastupdatedate as 'Day', SUBSTRING(lastupdatetime FROM -8 FOR 2) as 'Time' FROM ratingout where Telesales='" & cbTelesales.Text & "' and lastupdatedate= '" & dateWorkCheck.Text & "' and lastupdatedate is not null and lastupdatetime is not null ORDER BY lastupdatetime ;"
wcCommand.Connection = wcconn
wcCommand.CommandText = wQuery
Dim wData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(wData)
wData.Columns.Add("tt")
wData.Columns.Add("num")
wcData.Columns.Add("tt")
wcData.Columns.Add("num")
'dgvWorkCheck.AutoSizeRowsMode = DataGridViewAutoSizeRowMode.AllCells
Dim dr As DataRow
For Each dr In wData.Rows
If lastV Is Nothing OrElse Not ColumnEqual(lastV, dr("Time")) Then
''check if first value is nothing
If lastV = Nothing Then
lastV = "00"
l = "0"
Else
dr("tt") = lastV
dr("num") = l
'wcData.Tables("ratingout").Rows(I)("ID") = dr("ID")
End If
ListBox1.Items.Add(lastV & " <--> " & l)
lastV = dr("Time")
l = 1
ElseIf lastV Is Nothing OrElse ColumnEqual(lastV, dr("Time")) Then
l += 1
'Dim series1 As New Series()
'series1.Points.Add(l)
End If
For I = I To wData.Rows.Count
If I <> wData.Rows.Count Then
I += 1
If i = wData.Rows.Count Then
dr("tt") = lastV
dr("num") = l
ListBox1.BeginUpdate()
ListBox1.Items.Add(dr("Telesales") & " between[" & lastV & " and 17:00, ] <--> " & l & "[ records ]")
ListBox1.EndUpdate()
End If
GoTo n
Else
MsgBox("last data")
End If
Next
n:
Next
txtRec.Text = wData.Rows.Count
dgvWorkCheck.DataSource = wData
''chart
Dim ChartArea2 As ChartArea = New ChartArea()
Dim Legend2 As Legend = New Legend()
Dim Series2 As Series = New Series()
Dim Chart2 = New Chart()
Me.Controls.Add(Chart2)
ChartArea2.AxisX.LabelStyle.Angle = -90
ChartArea2.AxisX.LabelStyle.Interval = 1
ChartArea2.AxisY.LabelStyle.Angle = -90
ChartArea2.AxisY.LabelStyle.Interval = 5
ChartArea2.Name = "ChartArea2"
Chart2.ChartAreas.Add(ChartArea2)
Legend2.Name = "Legend2"
Chart2.Legends.Add(Legend2)
Chart2.Location = New System.Drawing.Point(12, 113)
Chart2.Name = "Chart2"
Series2.ChartArea = "ChartArea2"
Series2.Legend = "Legend2"
Series2.Name = "Series2"
Chart2.Series.Add(Series2)
Chart2.Size = New System.Drawing.Size(1145, 604)
Chart2.TabIndex = 0
Chart2.Text = "Chart2"
Chart2.Series("Series2").XValueMember = "tt"
Chart2.Series("Series2").YValueMembers = "num"
Chart2.DataSource = dgvWorkCheck.DataSource
Chart2.DataBind()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Exit Try
since the new data is inserted into a database, you will only need to rebind the gridview to it's source in order to display the new incoming data.
You should isolate the code that binds data to your chart in a function and have it called every time a new field gets inserted:
Function FillChartWithData()
Dim myData As New DataTable
wcAdapter.SelectCommand = wcCommand
wcAdapter.Fill(myData)
...
Chart1.Series("Series1").ValueMemberX = "table1"
Chart1.Series("Series1").ValueMembersY = "table2"
End Function
EDIT
I looked at your coded and it seems you're missing the part responsible for inserting new data inside the 'ratingout' table. You should create a function that allows you to insert new data, something along the line of:
Dim insertRating = "INSERT INTO ratingout VALUES (#NewTeleSalesName, #NewDate);"
Dim insertCmd As New MySqlCommand(insertRating, wcconn)
insertCmd.Parameters.Add("#NewTeleSalesName", MySqlDbType.VarChar, 255, "teleSalesName")
insertCmd.Parameters.Add("#NewDate", MySqlDbType.Datetime, 8, New DateTime(2010, 8, 5))
insertCmd.ExecuteNonQuery()
In order to update my chart bargraph named CashChart (which was databound to a BindingSource) I had to do the following:
To clear the chart information,
Clear the bounding source information
And then re-assign the bounding source information: for example:
CashChart.Series(0).Points.Clear()
CashChart.DataSource = ""
CashChart.DataSource = ESTADOINSTANTANEOBindingSource
Before, only my DataTable was updating, but after these commands, I was able to get the bargraph to update with new values in the table.