Update a chart automatically with a timer - vb.net

So, I am developing an application and I got stuck probably on a basic thing that I can't solve. I have a chart which is connected to a database and it will be running a query. I was able to do it, but the issue there I am facing is that it won't update unless I close and open the application.
I will show you the code that I am using and then explain it:
Public Sub UpdateChart()
Try
SQLCon = New SqlConnection
SQLCon.ConnectionString = "......................"
Timer1.Interval = 3000
Timer1.Start()
Dim sqlStatis As String = "SELECT Top 5 Filename, Filesize FROM infofile"
Dim da As New SqlDataAdapter(sqlStatis, SQLCon)
Dim ds As New DataSet()
da.Fill(ds, "infofile")
Chart1.DataSource = ds.Tables("infofile")
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
SQLCon.Dispose()
End Try
End Sub
Public Sub BuildChart()
Dim Chart1 = New Chart()
Dim ChartArea1 As ChartArea = New ChartArea()
Dim Legend1 As Legend = New Legend()
Dim Series1 As Series = New Series()
Me.Controls.Add(Chart1)
ChartArea1.Name = "ChartArea1"
Chart1.ChartAreas.Add(ChartArea1)
Legend1.Name = "Legend1"
Chart1.Legends.Add(Legend1)
Chart1.Location = New System.Drawing.Point(12, 12)
Chart1.Name = "Chart1"
Series1.ChartArea = "ChartArea1"
Series1.Legend = "Legend1"
Series1.Name = "Tamanho do ficheiro"
Chart1.Series.Add(Series1)
Chart1.Size = New System.Drawing.Size(600, 300)
Chart1.TabIndex = 0
Chart1.Text = "Chart1"
Chart1.Series("Tamanho do ficheiro").XValueMember = "Filename"
Chart1.Series("Tamanho do ficheiro").YValueMembers = "Filesize"
End Sub
This method will be called on the form and the data will be shown as I want. As you can see on the method I have a Timer and it will update the chart every 3 seconds or 3000 milliseconds.
Inside of the Timer I have this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
UpdateChart()
End Sub
And inside of the form I have this:
Public Sub Gráfico_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildChart()
UpdateChart()
End Sub
It doesn't gives me any error but it doesn't update even if I create a button called "Update Chart" and put the method already created inside of the button.
So do you have any ideia I could I solve my problem?

I would move
Timer1.Interval = 3000
Timer1.Start()
to the end of the Form Load
and Dim Chart1 as a form level variable and new it up in the Load as well

Related

How can I write a loop to replace this if statement for different buttons

I have an Access datatable named A. It has 90 rows and each row has 2 columns as follows:
I have a vb form that has 90 green buttons and code:
Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myConnection As New OleDbConnection(myConnString)
Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
myConnection.Open()
Dim reader As OleDbDataReader
Dim dt As New DataTable
dt.Load(myCommand.ExecuteReader)
If dt.Rows(0).Item(0).ToString = 1 Then
Button1.BackColor = Color.Red
Button1.FlatAppearance.BorderColor = Color.Red
End If
If dt.Rows(1).Item(0).ToString = 2 Then
Button2.BackColor = Color.Red
Button2.FlatAppearance.BorderColor = Color.Red
End If
End Sub
This works fine, but I don't want to repeat the same If block over and over again for 90 buttons. How can I write a loop with just one set of code for all 90 buttons?
Loop through your records and find the corresponding buttons:
For Each row As DataRow In dt.Rows
Dim buttonName as String = "button" & row(0).ToString()
Dim cntrls() As Control = Me.Controls.Find(buttonName, True)
If cntrls IsNot Nothing Then
Dim btn As Button = TryCast(cntrls(0), Button)
If btn IsNot Nothing Then
btn.BackColor = Color.Red
btn.FlatAppearance.BorderColor = Color.Red
End If
End If
Next
This is dependent on the buttons' naming scheme being consistent.
Using your own "words" :) maybe not the most efficient way but I just wanted to write this by reusing your code as much as possible...
Private Sub _1st_Floor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myConnection As New OleDbConnection(myConnString)
Dim myCommand As New OleDbCommand("SELECT ID FROM A WHERE Busy=True", myConnection)
myConnection.Open()
Dim reader As OleDbDataReader
Dim dt As New DataTable
dt.Load(myCommand.ExecuteReader)
For index As Integer = 1 To 90
If dt.Rows(index - 1).Item(0).ToString = index.ToString Then
Dim button As Button = CType(Me.Controls("Button" + index.ToString), Button)
button.BackColor = Color.Red
button.FlatAppearance.BorderColor = Color.Red
End If
Next
End Sub
I used this post to get controls by name String

Loop that creates labels that can open a new form

hey everyone can someone help me with some codes in vb.net
i created a loop that can generate labels with my OleDbDataReader
now i was wondering if i can make those labels open new form
and can i use the data in this label in my new form like the label text created !
here is my code :
Dim cnn As New OleDbCommand(query, con)
Dim cmd As New OleDbDataAdapter(cnn)
Dim dt As New DataTable()
cmd.Fill(dt)
Dim reader As OleDbDataReader
reader = cnn.ExecuteReader()
Dim number As Integer = 0
Dim location As Integer = 0
While reader.Read()
Dim sensibleFont As New Font("Segoe UI", 15)
Dim lb As New Label()
lb.Name = "labb" + number.ToString
lb.Size = New System.Drawing.Size(350, 40)
lb.Location = New System.Drawing.Point(50, 15 + location)
lb.Text = dt.Rows(number)(0).ToString()
lb.ForeColor = Color.Black
lb.Font = sensibleFont
GroupBox1.Controls.Add(lb)
Dim lb2 As New Label()
lb2.Name = "labs" + number.ToString
lb2.Size = New System.Drawing.Size(280, 40)
lb2.Location = New System.Drawing.Point(10, 5 + location)
lb2.Text = dt.Rows(number)(2).ToString()
lb2.ForeColor = Color.Black
lb2.Font = sensibleFont
GroupBox2.Controls.Add(lb2)
location += 40
number += 1
End While
con.Close()
Create a sub that does what you want.
Private Sub OpenForm()
Dim myForm As New MyForm()
myForm.Show()
End Sub
During label creation, add a click event that uses this sub as it's handler
AddHandler lb.Click, AddressOf OpenForm
As shown in the answer by A Friend, you can add a handler to a label's click event. Extending that to use the correct signature for the handler, you can get the object which raised the event and so use its properties, such as the .Text property:
Sub Label_Click(sender As Object, e As EventArgs)
Dim lbl = DirectCast(sender, Label)
Dim frm2 = New OtherForm(lbl.Text)
frm2.Show()
End Sub
To go with it, you will need a constructor (the Sub New) in the other form (which I named "OtherForm") like this:
Public Class OtherForm
Sub New()
InitializeComponent()
End Sub
Sub New(info As String)
InitializeComponent()
Label1.Text = info
End Sub
End Class
Where Label1 is just a label I put on OtherForm for testing purposes.
You might find the .Tag property of a control better for passing data as it can be any Object, e.g. an instance of a class.
I notice that you are reading the database twice: once to fill the datatable and then again as a count of the rows in the datatable, which is a bit wasteful. Also, you should dispose of a font when you have finished with it: the Using construct will take care of that for you, similarly for a connection to a database. Like this:
Sub PopulateGroupBox()
Dim connStr = "CONNECTION STRING HERE"
Dim query = "SQL QUERY HERE"
Dim dt As New DataTable()
Using con As New OleDbConnection(connStr)
Dim cnn As New OleDbCommand(query, con)
Dim cmd As New OleDbDataAdapter(cnn)
cmd.Fill(dt)
End Using
Dim location As Integer = 0
Using sensibleFont As New Font("Segoe UI", 15)
For i = 0 To dt.Rows.Count - 1
Dim lb1 As New Label()
lb1.Name = "labb" & i.ToString()
lb1.Size = New System.Drawing.Size(350, 40)
lb1.Location = New System.Drawing.Point(50, 15 + location)
lb1.Text = dt.Rows(i)(0).ToString()
lb1.ForeColor = Color.Black
lb1.Font = sensibleFont
AddHandler lb1.Click, AddressOf Label_Click
GroupBox1.Controls.Add(lb1)
Dim lb2 As New Label()
lb2.Name = "labs" & i.ToString()
lb2.Size = New System.Drawing.Size(280, 40)
lb2.Location = New System.Drawing.Point(10, 5 + location)
lb2.Text = dt.Rows(i)(2).ToString()
lb2.ForeColor = Color.Black
lb2.Font = sensibleFont
AddHandler lb2.Click, AddressOf Label_Click
GroupBox2.Controls.Add(lb2)
location += 40
Next
End Using
End Sub

How to update a Chart

I've just finished developing a piece of code where I am able to create a Chart and query from my database. Here I insert values from the database and it will show to the user.
I will post here the code that I've done to create a chart:
Public Sub BuildChart()
Try
SQLCon = New SqlConnection
SQLCon.ConnectionString = "........."
Dim sqlStatis As String = "SELECT Top 5 Filename, Filesize FROM infofile"
Dim Chart1 As New Chart()
Dim da As New SqlDataAdapter(sqlStatis, SQLCon)
Dim ds As New DataSet()
da.Fill(ds, "infofile")
Dim ChartArea1 As ChartArea = New ChartArea()
Dim Legend1 As Legend = New Legend()
Dim Series1 As Series = New Series()
Me.Controls.Add(Chart1)
ChartArea1.Name = "ChartArea1"
Chart1.ChartAreas.Add(ChartArea1)
Legend1.Name = "Legend1"
Chart1.Legends.Add(Legend1)
Chart1.Location = New System.Drawing.Point(12, 12)
Chart1.Name = "Chart1"
Series1.ChartArea = "ChartArea1"
Series1.Legend = "Legend1"
Series1.Name = "Tamanho do ficheiro"
Chart1.Series.Add(Series1)
Chart1.Size = New System.Drawing.Size(600, 300)
Chart1.TabIndex = 0
Chart1.Text = "Chart1"
Chart1.Series("Tamanho do ficheiro").XValueMember = "Filename"
Chart1.Series("Tamanho do ficheiro").YValueMembers = "Filesize"
Chart1.DataSource = ds.Tables("infofile")
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
SQLCon.Dispose()
End Try
End Sub
As you can see I've created a method which will be called in the form and the info will be shown there. Outside of everything I declared a variable Dim Chart1 As New Chart(). Now I want to create a method which allows me with a timer to update automatically the chart. So I should create another method called UpdateChart where I could insert there this:
Timer1.Interval = 3000
Timer1.Start()
But now I have no idea what should I use to update it every 3 secs or 3000 milliseconds.
On Load you want to call the BuildChart method and start the timer:
Private Sub frmTest_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
BuildChart()
With Timer1
.Enabled = True
.Interval = 3000
.Start()
End With
End Sub
For BuildChart you only need to create the chart itself and not bind the data.
Public Sub BuildChart()
Try
Dim Chart1 As New Chart()
Dim ChartArea1 As ChartArea = New ChartArea()
Dim Legend1 As Legend = New Legend()
Dim Series1 As Series = New Series()
Me.Controls.Add(Chart1)
ChartArea1.Name = "ChartArea1"
Chart1.ChartAreas.Add(ChartArea1)
Legend1.Name = "Legend1"
Chart1.Legends.Add(Legend1)
Chart1.Location = New System.Drawing.Point(12, 12)
Chart1.Name = "Chart1"
Series1.ChartArea = "ChartArea1"
Series1.Legend = "Legend1"
Series1.Name = "Tamanho do ficheiro"
Chart1.Series.Add(Series1)
Chart1.Size = New System.Drawing.Size(600, 300)
Chart1.TabIndex = 0
Chart1.Text = "Chart1"
Chart1.Series("Tamanho do ficheiro").XValueMember = "Filename"
Chart1.Series("Tamanho do ficheiro").YValueMembers = "Filesize"
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
SQLCon.Dispose()
End Try
End Sub
We then want UpdateChart to be called from the Timer.Tick event.
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
UpdateChart()
End Sub
Private Sub UpdateChart()
Chart1.Series(0).Points.Clear()
Chart1.DataSource = ""
SQLCon = New SqlConnection
SQLCon.ConnectionString = "............."
Dim sqlStatis As String = "SELECT Top 5 Filename, Filesize FROM infofile"
Dim da As New SqlDataAdapter(sqlStatis, SQLCon)
Dim ds As New DataSet()
da.Fill(ds, "infofile")
Chart1.DataSource = ds.Tables("infofile")
End Sub
Be aware though that this will create a lot of hits to your database.

Datagridview strange display error on init

upon initialization of my UI i get the following very strange behavior regarding to the drawing of the datagridview:
Basically, expect the first row header and the column headers (which i did not include in the pic) it looks like the DGV prints what is on the Screen "behind" his application.
What the hell is this and does anyone know a way to fix it?
Code of Container:
Public Class DGVControl
Dim dt As DataTable
Public Sub init()
dt = New DataTable
Dim arr(ldfAttributes.Count - 1) As String
Dim cms As New ContextMenuStrip
Dim i As Integer = 0
For Each att As String In Attributes.Keys
Dim cmsitem As New ToolStripMenuItem
dt.Columns.Add(att, GetType(String))
cmsitem.Name = att
cmsitem.Text = att
cmsitem.Owner = cms
cmsitem.CheckOnClick = True
cmsitem.Checked = my.Settings.shownColumns.Contains(att)
AddHandler cmsitem.CheckedChanged, AddressOf showOrHideColumn
cms.Items.Add(cmsitem)
arr(i) = "No Data"
i += 1
Next
For i = 1 To my.settings.anzEntries
dt.Rows.Add(arr)
Next
MainDGV.DataSource = dt
MainDGV.ContextMenuStrip = cms
For Each attName as String In Attributes.key
showOrHideColumn(cms.Items(attName), New EventArgs())
Next
MainDGV.RowHeadersWidth = 90
MainDGV.RowTemplate.Height = 40
MainDGV.RowHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.RowHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.ColumnHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.ColumnHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.BackgroundColor = Color.White
End Sub
Private Sub showOrHideColumn(sender As Object, e As EventArgs)
Dim cmsitem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
MainDGV.Columns(cmsitem.Name).Visible = cmsitem.Checked
End Sub
'taken from: http://stackoverflow.com/questions/710064/adding-text-to-datagridview-row-header
Private Sub nameRowHeaders(sender As Object, e As EventArgs) Handles MainDGV.DataBindingComplete
Dim dgv As DataGridView = CType(sender, DataGridView)
For i As Integer = 0 To dgv.RowCount - 1
dgv.Rows(i).HeaderCell.Value = ("Entry " &(i+1).toString())
Next
End Sub
End Class
EDIT:
As soon as you once select a row, all cells will be displayed in the right way until you restart the application

ListView in VB.NET (VS 2010)

I am trying to display sql database table data in a list view in my vb application. I have used the following code
Public Class Form1
Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim da As SqlClient.SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlClient.SqlConnection("Data Source=AYYAGARI-PC\WINCC;Initial Catalog=anand;Integrated Security=True")
conn.Open()
Dim strQ As String = String.Empty
strQ = "SELECT * FROM [anand].[dbo].[WINCC] ORDER BY [dateandtime]"
cmd = New SqlClient.SqlCommand(strQ, conn)
da = New SqlClient.SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
Try
Call Timer1_Tick(sender, e)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
For Each i As ListViewItem In ListView1.SelectedItems
ListView1.Items.Remove(i)
Next
Try
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The problem with the above code is that whenever i update the table data in sql (inserting or deleting data), the same doesnt get updated in list view. Kindly help me out with this.
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
conn = New SqlClient.SqlConnection("Data Source=AYYAGARI-PC\WINCC;Initial Catalog=anand;Integrated Security=True")
conn.Open()
Dim strQ As String = String.Empty
strQ = "SELECT * FROM [anand].[dbo].[WINCC] ORDER BY [dateandtime]"
cmd = New SqlClient.SqlCommand(strQ, conn)
da = New SqlClient.SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
Try
Call Timer1_Tick(sender, e)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try to add this code again to your button which made insert or update.
UPDATE
I give you another tips, that wont make your code so long and wasted memory or capacity..
Try to insert all the code to new sub, e.g :
private sub mycode
msgbox("Hello World")
end sub >> This code won't work when you debug, cause it just like a stored code, so need to be called to make it work
Private sub Form_load...... > E.g this is your form load code
call mycode >> Called the code above
end sub >> when you debug, your form will auto called the mycode