datagrid view change color depend of status in winform application - vb.net

I have a function like this:
Sub KPIColorchange()
'take 80 percenatge
Dim perc80 As Integer = 80
value80 = DefaultKPI * perc80 / 100
Dim carid As String
Dim strr As String = "select t.TBarcode as carid from Khanger_tbl k
inner join transaction_tbl t on k.transactid=t.transactID"
strr = strr + " where tid= " & tid & " and requested=1 and delivered=0 and status=3
and DATEDIFF(n, CAST(paydate AS DATETIME), GETDATE()) >=" & value80 & ""
Dim cmdr As New SqlCommand(strr, con.connect)
dr2 = cmdr.ExecuteReader
While dr2.Read
If dr2("carid") Is DBNull.Value Then
carid = ""
Else
carid = dr2("carid")
End If
Dim cnt As Integer = DGVall.Rows.Count
For i = 0 To cnt - 2
If DGVall.Rows(i).Cells(0).Value.ToString().Equals(carid) Then
DGVall.Rows(i).DefaultCellStyle.BackColor = Color.Fuchsia
End If
Next
End While
dr2.Close()
con.disconnect()
'take 100 percentage
Dim perc100 As Integer = 100
value100 = DefaultKPI * perc100 / 100
Dim str100 As String = "select t.TBarcode as carid from Khanger_tbl k
inner join transaction_tbl t on k.transactid=t.transactID"
str100 = str100 + " where tid= " & tid & " and requested=1 and delivered=0 and status=3 and
DATEDIFF(n, CAST(paydate AS DATETIME), GETDATE()) >=" & value100 & ""
Dim cmd100 As New SqlCommand(str100, con.connect)
dr2 = cmd100.ExecuteReader
While dr2.Read
If dr2("carid") Is DBNull.Value Then
carid = ""
Else
carid = dr2("carid")
End If
Dim cnt As Integer = DGVall.Rows.Count
For i = 0 To cnt - 2
If DGVall.Rows(i).Cells(0).Value.ToString().Equals(carid) Then
DGVall.Rows(i).DefaultCellStyle.BackColor = Color.OrangeRed
End If
Next
End While
dr2.Close()
con.disconnect()
End Sub
I have a grid view ,in that grid view i am loading some Requested carid we already set some time interval to Location.depend on the location time interval i have to change color in grid view
if the car requested time coming 80 percentage of location interval time then i will change to one color .
if the car requested time coming 100 percentage of location interval time then i will change to OrangeRed only this much things i am doing here..normally my datagrid view contains morethan 100 above records. this function i am calling in Timer_tick event in each one minute.
but becouse of this function my system get slow or some time system get hang.how i can optimize this code?
any help is very appreciable in advance

Related

On a VB form why are graphics disappearing when the form is first displayed?

I have a form which displays graphs of various kinds, taken from sales data from a database.
These graphs are drawn on panels on the form but I have had a very recent issue. Up until recently, the form displayed the graphs when it was displayed but now the graphs appear then disappear and I cannot figure out why.
Here is a link to a Vimeo video showing the behaviour: https://vimeo.com/575969787
When the form is loaded a procedure is called in the Form_Shown event which draws the graphs - for ease of understanding I have restricted this to one graph only.
Private Sub FormDashboard_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'Once form is initialised and shown run all the reports
RunReports(True)
End Sub
Private Sub RunReports(All As Boolean)
'Display these reports
DrawDepartment(PanelFood, TableDepartment)
'DrawDepartment(PanelWine, TableDepartment)
'DrawDivision(PanelDivision, TableDepartment)
'DrawCLA(PanelCLA, TableCLA)
''If all = true then also display MAT
'If (All = True) Then
' DrawMAT(PanelMAT, TableMAT)
'End If
End Sub
Public Shared Sub DrawDepartment(TargetPanel As Panel, TableGraph As DataTable)
'Graphics object
Dim Dep_Graph As Graphics = TargetPanel.CreateGraphics
Dim Offset As Integer = 45
Dim DepName As String = ""
'Graph area
With TargetPanel
GraphHeight = .Height - (Offset + Gap)
GraphWidth = .Width - (2 * Gap)
GraphXOrigin = Gap
GraphYOrigin = (Offset + Gap)
End With
Dim Filter As String = "" 'Filter used for querying the data table
Dim FoundMax() As DataRow 'A data row generated by a filter
Dim FoundRows() As DataRow 'A data row generated by a filter
'The data table has a max value for food sales in the given period
If (TargetPanel.Name.Contains("Food")) Then
Filter = "Department LIKE 'F%' OR Department LIKE 'S%'"
Else
Filter = "Department LIKE 'W%'"
End If
Select Case Report
Case ReportMode.Day
TableGraph.DefaultView.Sort = "Day DESC"
FoundMax = TableGraph.Select(Filter)
MaxDataValue = FoundMax(0).Item("Day")
Case ReportMode.Week
TableGraph.DefaultView.Sort = "Week DESC"
FoundMax = TableGraph.Select(Filter)
MaxDataValue = FoundMax(0).Item("Week")
Case ReportMode.Month
TableGraph.DefaultView.Sort = "Month DESC"
FoundMax = TableGraph.Select(Filter)
MaxDataValue = FoundMax(0).Item("Month")
Case ReportMode.Year
TableGraph.DefaultView.Sort = "Year DESC"
FoundMax = TableGraph.Select(Filter)
MaxDataValue = FoundMax(0).Item("Year")
End Select
TableGraph.DefaultView.Sort = "Department"
'Select only the food department values
If (TargetPanel.Name.Contains("Food")) Then
Filter = "Department LIKE 'F%' OR Department LIKE 'S%'"
Else
Filter = "Department LIKE 'W%'"
End If
FoundRows = TableGraph.Select(Filter)
'Calculate the width of each column
Dim NumberOfColumns As Integer = (FoundRows.GetUpperBound(0) + 1)
ColWidth = (GraphWidth - ((NumberOfColumns) * Gap)) / NumberOfColumns
'Using the graphics object draw the columns
With Dep_Graph
MessageBox.Show("Clearing graph area")
'Using the FoundMax data row extract the Day max value
ClearGraph(TargetPanel)
For Counter As Integer = 0 To FoundRows.GetUpperBound(0)
Select Case Report
Case ReportMode.Day
DataValue = FoundRows(Counter).Item("Day")
DepName = FoundRows(Counter).Item("Department")
If (TargetPanel.Name.Contains("Wine")) Then
ReportLabel(Counter + 12).Text = GetLabelData(DepName, DataValue)
Else
ReportLabel(Counter).Text = GetLabelData(DepName, DataValue)
End If
Case ReportMode.Week
DataValue = FoundRows(Counter).Item("Week")
DepName = FoundRows(Counter).Item("Department")
If (TargetPanel.Name.Contains("Wine")) Then
ReportLabel(Counter + 12).Text = GetLabelData(DepName, DataValue)
Else
ReportLabel(Counter).Text = GetLabelData(DepName, DataValue)
End If
Case ReportMode.Month
DataValue = FoundRows(Counter).Item("Month")
DepName = FoundRows(Counter).Item("Department")
If (TargetPanel.Name.Contains("Wine")) Then
ReportLabel(Counter + 12).Text = GetLabelData(DepName, DataValue)
Else
ReportLabel(Counter).Text = GetLabelData(DepName, DataValue)
End If
Case ReportMode.Year
DataValue = FoundRows(Counter).Item("Year")
DepName = FoundRows(Counter).Item("Department")
If (TargetPanel.Name.Contains("Wine")) Then
ReportLabel(Counter + 12).Text = GetLabelData(DepName, DataValue)
Else
ReportLabel(Counter).Text = GetLabelData(DepName, DataValue)
End If
End Select
If (MaxDataValue > 0) Then
'Set column height to a scale of the maximum value
ColHeight = (DataValue * GraphHeight) / MaxDataValue
End If
'Set colours
PenWWC.Color = Colors(Counter + 2)
BrushWWC = New SolidBrush(Colors(Counter + 2))
'Draw and fill
DrawColumn(Dep_Graph, GraphXOrigin, TargetPanel.Height - ColHeight - Offset, ColWidth, ColHeight, PenWWC, BrushWWC)
'Reset X0 to the next point
GraphXOrigin = GraphXOrigin + ColWidth + Gap
Next
End With
GraphXOrigin = Gap
Dep_Graph.Dispose()
End Sub
As can be seen in the video I have included a message box at the point where I clear the graphing area to show that this is NOT what is happening.
As I say, up until recently the form displayed with graphs showing; no changes have been made to this section of the application code so i don't know what is happening.
Further, as shown in the video, if I select the date for which the form is set, the graphs appear and if I change date, the new graphs appear, without problem.
Any suggestions most welcome. AFAIK I have posted all the relevant code here.
TIA,
Dermot

How to check if an item in a table is between two times M:N

I have a many to many relationship between two entities. Computer and Booking, with the link entity being BookingToComputer which contains bookingID and computerID. Im trying to check that the computer is available for booking before adding it to the tables.
So I've selected the date, time, and hours of use (3 attributes in the booking table) of existing Booking records. I've created two time variable, start time (totalTime) and the end time of a booking (endtime). I've tried to put a loop to where each item in my list would go through all the selected rows from a datagridview to check if they match but I don't think I got it quite right and at this point im super confused.
Dim Part1 As String = txtTime.Text + ":00:00"
Dim Part2 As String = "00:" + txtTime1.Text + ":00"
Dim Part3 As String = "00:00:" + txtTime2.Text
Dim Time1 As TimeSpan = TimeSpan.Parse(Part1)
Dim Time2 As TimeSpan = TimeSpan.Parse(Part2)
Dim Time3 As TimeSpan = TimeSpan.Parse(Part3)
Dim TotalTime As TimeSpan = Time1 + Time2 + Time3
SQL.AddParam("#Time", txtTime.Text & ":" & txtTime1.Text & ":" & txtTime2.Text)
SQL.AddParam("#Date", txtDate.Text)
SQL.ExecQuery("SELECT bc.Computer_ID, hours_of_use, time_of_use FROM BookingToComputer AS bc, Computer AS c, Booking AS b
WHERE bc.Booking_ID = b.Booking_ID AND c.Computer_ID = bc.Computer_ID AND b.date_of_use = #Date AND b.time_of_use <= #Time;")
DataGridView2.DataSource = SQL.DBDT
If DataGridView2.Rows.Count() > 0 Then
'cell1 contains the hours used and time contains the time'
Dim TimeInt As Integer = DataGridView2.Rows(0).Cells(1).Value
Dim TimeInt2 As TimeSpan = DataGridView2.Rows(0).Cells(2).Value
Dim Addit As String = TimeInt.ToString + ":00:00"
Dim interv As TimeSpan = TimeSpan.Parse(Addit)
Dim endtime As TimeSpan = TimeInt2 + interv
Dim rowpass As Integer = 0
For Each x In listpick
Dim CompID As Integer = DataGridView2.Rows(rowpass).Cells(0).Value
If x = CompID Then
If endtime > TotalTime Then
MsgBox(x & " is already reserved.")
Else
MsgBox("diff time, same comp")
End If
Else
MsgBox("Good time - diff comp")
End If
rowpass = rowpass + 1
Next
End If

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

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.