How to update a Chart - vb.net

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.

Related

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

Update a chart automatically with a timer

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

Printing dataGridView in Tables (vb2010)

i'm new to vb programming. i'm using vb2010 I'm doing a database application now. It works fine. But i have to add another task. That is to print the data on the DGV in table form. I've done a lot of research about this but haven't found it. Any help or response will be highly appreciated.
i'm sorry, here is my Code: It works but it prints just a black document.
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\IT-PC\Documents\Visual Studio 2010\Projects\MaterialSectionIS\MaterialSectionIS\My Project\materialsInventory.accdb"
Dim MyPrintDocument As PrintDocument = New PrintDocument
Dim MyDataGridViewPrinter As DataGridViewPrinter
Dim MyPrintDialog As PrintDialog = New PrintDialog()
MyPrintDialog.AllowCurrentPage = False
MyPrintDialog.AllowPrintToFile = False
MyPrintDialog.AllowSelection = False
MyPrintDialog.AllowSomePages = True
MyPrintDialog.PrintToFile = False
MyPrintDialog.ShowHelp = False
MyPrintDialog.ShowNetwork = False
'Dim commdata As New OleDb.OleDbCommand("SELECT * FROM metal WHERE itemCodeM = #tbItemCodeMetal", myConnection)
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [metal]", MyConn)
da.Fill(ds, "metal")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
If MyPrintDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then Return False
MyPrintDocument.DocumentName = "metal"
MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings
MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings
MyPrintDocument.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)
If MessageBox.Show("Do you want the report to be centered on the page", "METAL - Center on Page", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
MyDataGridViewPrinter = New DataGridViewPrinter(DataGridView1, MyPrintDocument, True, True, "metal", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
Else
MyDataGridViewPrinter = New DataGridViewPrinter(DataGridView1, MyPrintDocument, False, True, "metal", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
End If
Return True
End Function
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim more As Boolean
Try
more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
If more Then e.HasMorePages = True
Catch Ex As Exception
MessageBox.Show(Ex.Message & vbCrLf & Ex.StackTrace, MyConstants.CaptionFehler, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyPrintDocument As PrintDocument = New PrintDocument
If SetupThePrinting() Then
Dim MyPrintPreviewDialog As PrintPreviewDialog = New PrintPreviewDialog()
MyPrintPreviewDialog.Document = MyPrintDocument
MyPrintPreviewDialog.ShowDialog()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim MyPrintDocument As PrintDocument = New PrintDocument
If SetupThePrinting() Then MyPrintDocument.Print()
End Sub

Data table is not functioning properly

Data table is not functioning properly, it even causes my dynamic table layout not showing. And I have absolutely no idea what went wrong. By the way, i'm a beginner.
Public Class ListItem
Dim dt As System.Data.DataTable
Private Sub ListItem_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim conn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|\SMS.accdb"
Dim sqlstr As String = "Select * from ItemList"
Dim dtad As New OleDb.OleDbDataAdapter(sqlstr, conn)
dtad.Fill(dt)
dtad.Dispose()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim ListTable As New TableLayoutPanel()
ListTable.AutoSize = True
ListTable.AutoSizeMode = Windows.Forms.AutoSizeMode.GrowAndShrink
ListTable.Location = New Point(20, 20)
ListTable.BackColor = Color.White
ListTable.ColumnCount = CInt(dt.Columns.Count)
ListTable.RowCount = CInt(dt.Rows.Count)
ListTable.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single
For colindex = 0 To dt.Columns.Count - 1
For rowindex = 0 To 0
Dim newlabel As New Label()
newlabel.Location = New Point(10, 10)
newlabel.Name = "label" & colindex
newlabel.Font = New Drawing.Font("Microsoft Sans Serif", 16, FontStyle.Underline)
newlabel.Text = dt.Columns(colindex).ColumnName
newlabel.AutoSize = True
ListTable.Controls.Add(newlabel, colindex, rowindex)
Next
Next
Controls.Add(ListTable)
End Sub
End Class
It gives me this error:
An unhandled exception of type 'System.NullReferenceException' occurred in StockManagementSystem.exe
Additional information: Object reference not set to an instance of an object.
Very first line inside the class. Change it from this:
Dim dt As System.Data.DataTable
to this:
Dim dt As New System.Data.DataTable

DataGridView with ODBC data adapter

I am load data from database to my datagridview through ODBC adapter.
cmd = New Odbc.OdbcCommand(sql, cn)
adp = New Odbc.OdbcDataAdapter(cmd)
adp.Fill(ds, "temp2")
bs.DataSource = ds
DataGridView2.DataSource = bs
That way I can change and update data in database "lively".
But I have different situation now.
For changing data I have to go on grid's doubleclick to another form and when I come back I would like that my datagridview show changes in certain row.
This is what I try:
Dim fl As New dataform
With fl
.StartPosition = FormStartPosition.Manual
.aCallerLocation = Me.Location
.ShowDialog()
End With
fl = Nothing
Dim c_builder As New Odbc.OdbcCommandBuilder(adp)
Dim o As Integer
Try
o = adp.Update(ds, "temp2")
MsgBox(o)
Catch ex As Exception
MsgBox(ex.Message)
End Try
But I can't simply get it whole day! There is no exception generated but "o" is allways zero.
What do I do wrong and how to get this functionality to see changes in the row after returnimg from "dataform"?
Try this
cmd = New Odbc.OdbcCommand(sql, cn)
adp = New Odbc.OdbcDataAdapter(cmd)
Dim c_builder As New Odbc.OdbcCommandBuilder(adp)
adp.Fill(ds, "temp2")
bs.DataSource = ds
DataGridView2.DataSource = bs
and this
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dsChange As DataSet = New DataSet
'add record
If (ds.HasChanges(DataRowState.Added)) Then
dsChange = ds.GetChanges(DataRowState.Added)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Dimasukan")
End If
End If
'Modified record
If (ds.HasChanges(DataRowState.Modified)) Then
dsChange = ds.GetChanges(DataRowState.Modified)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Dihapus")
End If
End If
'Delete record
If (ds.HasChanges(DataRowState.Deleted)) Then
dsChange = ds.GetChanges(DataRowState.Deleted)
Dim rowchange As Integer
rowchange = adp.Update(dsChange, "temp2")
If (rowchange > 0) Then
MessageBox.Show(rowchange.ToString() & " Record Berhasil Diubah")
End If
End If
'Menerapkan perubahan
ds.AcceptChanges()
'Refresh(DataGrid)
DataGridView2.Refresh()
End Sub