Custom label for vb chart - vb.net

#Custom label for vb chart#
I have a datatable like this
XValue
YValue
Title
1
1
A
2
2
B
3
3
C
I want to display a vb chart like this
6|
5|
4|
3| *C
2| *B
1| *A
0|______________________
0 1 2 3 4 5 6 7 5 8 9
so far i can only display this
6|
5|
4|
3| *3
2| *2
1| *1
0|______________________
0 1 2 3 4 5 6 7 5 8 9
this is my code below
Chart20.ChartAreas(0).AxisX.Minimum = 60
Chart20.ChartAreas(0).AxisX.Maximum = 220
Chart20.Series("TEMP").Points.Clear()
Try
CONN.Open()
COMMAND = CONN.CreateCommand
QUERY = "SELECT XValue,YValue,Title FROM vitals"
COMMAND = New MySqlCommand(QUERY, CONN)
READER = COMMAND.ExecuteReader
While READER.Read
Chart20.Series("TEMP").Points.AddXY(READER.GetString("YValue"), READER.GetString("XValue"))
End While
CONN.Close()
Catch ex As Exception
CONN.Close()
MsgBox(ex.ToString, MsgBoxStyle.Critical)
End Try
Can you help me out pls

If you set the .Label, .Font, .LabelBackColor, and .LabelForeColor properties you can see the labels of the points, e.g. I put a Chart control on a Form with this code:
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Class Datum
Property X As Integer
Property Y As Integer
Property Title As String
Sub New(x As Integer, y As Integer, t As String)
Me.X = x
Me.Y = y
Me.Title = t
End Sub
End Class
Sub ShowPointLabels()
Dim data = New List(Of Datum) From {New Datum(1, 1, "A"),
New Datum(2, 2, "B"),
New Datum(3, 3, "C")}
Chart1.Series.Clear()
Dim ds As New Series("Sample")
ds.ChartType = SeriesChartType.Point
Dim fnt = New Font("Arial", 12)
For Each d In data
Dim n = ds.Points.AddXY(d.X, d.Y)
Dim p = ds.Points(n)
p.Font = fnt
p.Label = d.Title
p.LabelBackColor = Color.PaleGoldenrod
p.LabelForeColor = Color.DarkBlue
p.LabelToolTip = "This is the label for " & d.Title
Next
Chart1.Series.Add(ds)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ShowPointLabels()
End Sub
End Class
To get this:
Also, it would be better to read all the data from the database in one step, in the next step add the data to the chart series, and finally add the series to the chart. That keeps the time that the connection to the database is open to a minimum and avoids the time taken to update the chart every time a point is added.

Sub ShowPointLabels()
Chart20.Series("TEMP").Points.Clear()
Try
CONN.Open()
COMMAND = CONN.CreateCommand
QUERY = "SELECT * FROM vitals"
COMMAND = New MySqlCommand(QUERY, CONN)
READER = COMMAND.ExecuteReader
For Each d In READER
Chart20.Series("TEMP").Points(Chart20.Series("TEMP").Points.AddXY(READER.GetString("XValue"), READER.GetString("YValue"))).Label = READER.GetString("Title")
Next
CONN.Close()
Catch ex As Exception
CONN.Close()
MsgBox(ex.ToString, MsgBoxStyle.Critical)
End Try
End Sub
I modified #Andrew Morton Answer to a simplified result and it works perfectly for me. I hope this helps somebody as well

Related

For loop with Datagridview1.SelectedRows().cells().value has 'Index was out of range.' [vb.net]

My values in Datagridview is
| warranty |
---------------
| 0001 |
| 0002 |
| 0003 |
| 0004 |
values from code :
Private Sub UpdateGrid()
Dim str As String = "select Warranty from TBwarranty"
ds = New DataSet
da = New OleDbDataAdapter(str, connection)
da.Fill(ds, "a")
DataGridView1.DataSource = ds.Tables("a")
End Sub
Please can someone really tell me what's wrong with this code that I'm having this error:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
At first I coding:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim c As Integer = DataGridView1.SelectedRows.Count() - 1
For i As Integer = 0 To c
Dim deleteQuery As String = "DELETE from TBwarranty WHERE warranty='" & DataGridView1.SelectedRows(i).Cells(0).Value & "'"
Try
T.ExecuteQuery(deleteQuery, connection) 'This my public sub in other class [ command.ExecuteNonQuery() ]
UpdateGrid()
Catch ex As System.Data.OleDb.OleDbException
MsgBox(ex.Message)
MessageBox.Show("Fail inserted.")
End Try
Next
End Sub
Then there was a problem error above.
Then I tried coding:
Dim c As Integer = DataGridView1.SelectedRows.Count() - 1
For i As Integer = 0 To c
Dim deleteQuery As String = "DELETE from TBwarranty WHERE warranty='" & DataGridView1.SelectedRows(i).Cells(0).Value & "'"
Console.WriteLine(deleteQuery)
Next
It's don't have any error and out put in console is true value.
I don't understand why is this? What wrong? and How do I? Thanks for the assistance.
From the advice of comment. Now I can solve the error.
Dim c As Integer = DataGridView1.SelectedRows.Count() - 1
For i As Integer = 0 To c
Dim deleteQuery As String = "DELETE from TBwarranty WHERE warranty='" & DataGridView1.SelectedRows(i).Cells(0).Value & "'"
Console.WriteLine(deleteQuery)
Try
T.ExecuteQuery(deleteQuery, connection)
Catch ex As System.Data.OleDb.OleDbException
MsgBox(ex.Message)
MessageBox.Show("Failed inserted.")
End Try
Next
UpdateGrid()

Datagridview CheckboxColumn Shaded or (X) Mark when unchecked

Good Morning
I have a column in DataGridView that generates checkbox and in relation to that I have also a lot of columns in my table that is called 2016,2017 and so on and all of that is TinyInt
Now here is the image for both of them:
Now here is my question, instead of uncheck how can make it shaded or X mark in the DataGridView Column?
here is my code in populating the DataGridView:
Dim sql1 As MySqlCommand = New MySqlCommand("Select * from period_closure", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
DataGridView1.DataSource = ds1.Tables(0)
con1.Close()
ds1.Tables(0).Columns(2).DataType = GetType(Boolean)
Me.DataGridView1.Columns(0).Frozen = True
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
DataGridView1.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
Next
DataGridView1.Columns("PeriodID").Visible = False
DataGridView1.Columns(0).DefaultCellStyle.BackColor = Color.LightBlue
First of all download 'X' image in google, or create your own.
then try to add this in your code.
Private Sub CheckBox1_Paint(sender As Object, e As PaintEventArgs) Handles CheckBox1.Paint
If CheckBox1.Checked = False Then
Try
Dim newImage As Image = Image.FromFile("E:\Projects\Library\BER-X.jpg")
Dim x As Single = 0
Dim y As Single = 0
Dim width As Single = CheckBox1.Width 'You can also try this CheckBox1.Width - 3
Dim height As Single = CheckBox1.Height 'You can also try this CheckBox1.Height - 3
e.Graphics.DrawImage(newImage, x, y, width, height)
Catch ex As Exception
End Try
End If
End Sub
the X mark in the checkbox is not accurate in the position but you can fix it by your self. Try it and Explore it to fit it in your system. :)
Hope this will help you.

How to merge columns/cells datagridview vb.net

I've been trying to merge columns in a datagridview after I add some values the way I want, yet sometimes it works, sometimes it doesn't. I can try this if you add 2 datagridviews, one with 6 columns and the other with 1 column.
I'm using extra cells to "store" some values and then delete them .
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i = 0 To DataGridView1.RowCount - 1
For j = 0 To DataGridView1.RowCount - 1
If i > j Then
'If DataGridView1(0, i).Value = DataGridView1(0, j).Value Then
If DataGridView1(0, i).Value = DataGridView1(0, j).Value Then
DataGridView1(3, i).Value = DataGridView1(1, i).Value + DataGridView1(1, j).Value
End If
End If
If i < j Then
'If DataGridView1(0, i).Value = DataGridView1(0, j).Value Then
If DataGridView1(0, i).Value = DataGridView1(0, j).Value Then
DataGridView1(4, i).Value = DataGridView1(1, i).Value + DataGridView1(1, j).Value
End If
End If
If i = j Then
DataGridView1(5, i).Value = DataGridView1(1, i).Value
End If
Next
Next
Call lezgo()
End Sub
Private Sub lezgo()
Dim i As Integer
For i = 0 To DataGridView1.ColumnCount - 1
Next
If i > 0 Then
DataGridView2.Rows.Add(i)
End If
For i = 0 To DataGridView1.ColumnCount - 1
DataGridView2(0, i).Value = DataGridView1(3, i).Value + DataGridView1(4, i).Value + DataGridView1(5, i).Value
Next
DataGridView1.Columns.Remove(Column4)
DataGridView1.Columns.Remove(Column5)
DataGridView1.Columns.Remove(Column6)
End Sub
I know it's really bad what I'm doing, but it kinda worked. But now I want to optimize this, and I can't figure this out..
When I'm not able to do this, it shows the error "System.InvalidCastException" .
I've googled a bit and I see no similar project.. Tks!
EDIT:
1| A| one
2| B| two
3| A| three
2| C| four
1| D| five
4| B| six
i want to->
1| A| one |AD | | | |AD this is dgv2
2| B| two |BC |CE | | |BCE
3| A| three | | |A | |A
2| C| four |BC |CE | | |BCE
1| D| five |AD | | | |AD
4| B| six | | |B | |B
2| E| seven |BC |CE | | |BCE
Try this...
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder = "Path to your CSV folder (do not include the file name here)"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
Dim dt As New DataTable
' change Test.csv to your csv file name here
Try
Using Adp As New OleDbDataAdapter("Select * from [csv.csv]", CnStr)
Adp.Fill(dt)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
dt.Columns.Add("New Data", Type.GetType("System.String"))
For Each DataRow In dt.AsEnumerable
' Get the data for new column
Dim query = From r In dt.AsEnumerable() Where r.Field(Of Integer)("F1") = DataRow("F1") Select r.Field(Of String)("F2")
' Join it together ad put it in the DataTable
DataRow("New Data") = String.Join("", query)
Next
DataGridView1.DataSource = dt
End Sub
End Class
Store your 3 columns of data data in a file called 'csv.csv'. and remember to set the path to the folder of the csv file in the code above (at the Dim folder = .....) you need to have the data in the format like below...
1, A, one
2, B, two
3, A, three
2, C, four
1, D, five
4, B, six
2, E, seven
I tried using the '|' but don't have the time right now to get that working, so i used a ',' to seperate the values in the csv file
Anyway, when you run the code, the 4th column is filled dynamically with the correct codes.... Hope that helps.....
you can also use the same logic to update the 4th column as you manually enter new rows\data directly into the DataGridView1 control in the DataGridView1_CellEndEdit event....
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
For Each DataRow In dt.AsEnumerable
' Get the data for new column
Dim query = From r In dt.AsEnumerable() Where r.Field(Of Integer)("F1") = DataRow("F1") Select r.Field(Of String)("F2")
' Join it together ad put it in the DataTable
DataRow("New Data") = String.Join("", query)
'dt.Rows(1)("New Data") = String.Join("", query)
Next
End Sub
you will also have to move the declaration for the DataTable to the top of the Form Class like so....
Public Class Form1
Private dt As New DataTable

how to update specific cell in data grid view using SQL and VB.net

I am trying to update a specific cell in datagridview using vb.net and sql ( or any other method)
I am using this code to split somme strings and save it into database.
Private Sub SalveazaData()
Dim list As String() = rtbComData.Text.Split(Environment.NewLine.ToCharArray())
SmdDataDataSet1.SearchAdrese.Rows.Clear()
SmdTableTableAdapter.ClearSearchAdrese()
Me.SearchAdreseTableAdapter.Update(Me.SmdDataDataSet1.SearchAdrese)
For Each Row As String In list
If Not (Row = "AT+DSCAN" Or Row = "OK" Or Row = "" Or Row = "AT+RSSI") Then
Dim s As String() = Split(Row, "|")
Dim aRow As smdDataDataSet1.smdTableRow = SmdDataDataSet1.smdTable.NewsmdTableRow()
aRow.Model = s(0)
aRow.AdresaUnica = s(1)
aRow.StatusModul = "ACTIVE"
Try
SmdDataDataSet1.SearchAdrese.Rows.Add(s(1))
SmdDataDataSet1.smdTable.Rows.Add(aRow)
Catch ex As Exception
Dim u As String
u = SmdTableTableAdapter.UpdateInactivActiv()
End Try
End If
Next
'selectzr()
salveaza()
status()
DataGridView1.Refresh()
End Sub
The table has the columns
Model | Adresa Unica | Status | time | InstAddress |
ZR 123456 active
ZR 654321 active
What i want to do is update the row with the address "123456" or "654321" and write in their specific cell , in this case the cell from the column | time | a value .
Can you please help me .?
I have made some digging and i have fund an answer.
please see below the code i've used in my application
Private Sub GroupCommandRtime()
Dim list As String() = rtbComData.Text.Split(Environment.NewLine.ToCharArray())`enter code here`
Dim ListaAdrese As List(Of String) = GetAdreseID()
For Each Row As String In list
For Each _Adresa As String In ListaAdrese
If Not (Row = "at+remote=" Or Row = "AT+RSSI" Or Row = "OK") Then
Try
Dim s As String() = Split(Row, " ")
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database\smdData.mdf;Integrated Security=True;User Instance=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE smdTable SET datetime='" + s(3) + "' WHERE AdresaUnica = '" + s(0) + "'"
cmd.ExecuteNonQuery()
Me.SmdTableTableAdapter.Fill(Me.SmdDataDataSet1.smdTable)
DataGridView1.Refresh()
Catch ex As Exception
End Try
End If
Next
Next
End Sub

DataGridView not Refreshing

I have a SQL table that looks similar to this:
1 | a | stuff...
2 | a | stuff...
3 | b | stuff...
4 | a | stuff...
5 | b | stuff...
I only want to show:
3 | b | stuff...
5 | b | stuff...
So I use this code to load the DataGridView:
Private Sub GetData()
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
' Create an instance of a DataAdapter.
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstTbl.FillSchema(dsNewInst, SchemaType.Source)
daInstTbl.Fill(dsNewInst)
' Create a new instance of a DataTable
MyDataTable = dsNewInst.Tables(0)
daInstTbl.Update(dsNewInst)
End Sub
Private Sub InitializeDataGridView()
Try
' Set up the DataGridView.
With Me.DataGridView1
' Set up the data source.
.DataSource = MyDataTable
End With
Catch ex As SqlException
MessageBox.Show(ex.ToString, _
"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
System.Threading.Thread.CurrentThread.Abort()
End Try
End Sub
Everything works great and until I want to delete 3 and renumber 4 and 5 down one to become 3 and 4. I have loops handling everything and the database is receiving the correct data except my DataGridView only shows the updates when I restart the program.
Here's my delete code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim daInstDeleteTbl As New SqlDataAdapter("SELECT * FROM Table", objConn)
Dim dsDeleteInst As New DataSet
Dim MyDeleteTable As DataTable
' Create an instance of a DataSet, and retrieve data from the Authors table.
daInstDeleteTbl.FillSchema(dsDeleteInst, SchemaType.Source)
daInstDeleteTbl.Fill(dsDeleteInst)
' Create a new instance of a DataTable
MyDeleteTable = dsDeleteInst.Tables(0)
'Begin Delete Code
Dim DeleteID, DeleteIndex As Integer
Dim MadeChange As Boolean = False
Integer.TryParse(TextBox1.Text, DeleteID)
Dim dgvIndexCount As Integer = MyDeleteTable.Rows.Count - 1
If MyDeleteTable.Rows(dgvIndexCount).Item(0) > DeleteID Then
Dim counter As Integer = -1
For Each row As DataRow In MyDeleteTable.Rows
counter += 1
If row.Item("Column") = DeleteID Then
DeleteIndex = counter
End If
Next
MadeChange = True
End If
drCurrent = MyDeleteTable.Rows.Find(DeleteID)
drCurrent.Delete()
If MadeChange = True Then
Dim i As Integer = 0
For i = DeleteIndex + 1 To dgvIndexCount
MyDeleteTable.Rows(i).Item(0) = MyDeleteTable.Rows(i).Item(0) - 1
Next
End If
'Send Changes to SQL Server
Dim objCommandBuilder As New SqlCommandBuilder(daInstDeleteTbl)
daInstDeleteTbl.Update(dsDeleteInst)
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
Dim objCommandReBuilder As New SqlCommandBuilder(daInstTbl)
daInstTbl.Update(dsNewInst)
End Sub
I think I am doing a lot of extra work just to do this wrong. Any ideas? Thanks.
When you invoke SqlDataAdapter.Update() the adapter updates the values in the database by executing the respective INSERT, UPDATE, or DELETE (from MSDN). The SELECT command is not executed. So you need to do it like this:
Insert/Update/Delete:
daInstTbl.Update(dsNewInst)
Select:
daInstTbl.Fill(dsNewInst)
Commit:
dsNewInst.AcceptChanges()
Example
Private connection As SqlConnection
Private adapter As SqlDataAdapter
Private data As DataSet
Private builder As SqlCommandBuilder
Private grid As DataGridView
Private Sub InitData()
Me.SqlSelect(firstLoad:=True, fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
Me.grid.DataSource = Me.data
Me.grid.DataMember = "Table"
End Sub
Public Sub SaveData()
Me.SqlInsertUpdateAndDelete()
Me.SqlSelect(fillLoadOption:=LoadOption.OverwriteChanges, acceptChanges:=True)
End Sub
Public Sub RefreshData(preserveChanges As Boolean)
Me.SqlSelect(fillLoadOption:=If(preserveChanges, LoadOption.PreserveChanges, LoadOption.OverwriteChanges))
End Sub
Private Sub SqlSelect(Optional firstLoad As Boolean = False, Optional ByVal fillLoadOption As LoadOption = LoadOption.PreserveChanges, Optional acceptChanges As Boolean = False)
If (firstLoad) Then
Me.data = New DataSet()
Me.connection = New SqlConnection("con_str")
Me.adapter = New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", connection)
Me.builder = New SqlCommandBuilder(Me.adapter)
End If
Me.connection.Open()
If (firstLoad) Then
Me.adapter.FillSchema(Me.data, SchemaType.Source, "Table")
End If
Me.adapter.FillLoadOption = fillLoadOption
Me.adapter.Fill(Me.data, "Table")
If (acceptChanges) Then
Me.data.Tables("Table").AcceptChanges()
End If
Me.connection.Close()
End Sub
Private Sub SqlInsertUpdateAndDelete()
If (Me.connection.State <> ConnectionState.Open) Then
Me.connection.Open()
End If
Me.adapter.Update(Me.data, "Table")
Me.connection.Close()
End Sub
PS: (Untested code)
My solution was to change the way I was declaring variables. Before I had:
Dim daInstTbl As _
New SqlDataAdapter("SELECT * FROM Table WHERE Column = 'b'", objConn)
The affect was that recalling the subroutine ignored this line because the variable daInstTbl was already declared previously. The solution was:
' Delete old instance of a Data____ classes
da = Nothing
ds = Nothing
dt = Nothing
If GetAll = False Then
da = New SqlDataAdapter(sSelCmd, objConn)
Else
da = New SqlDataAdapter(sSelAllCmd, objConn)
End If
' Create an instance of a DataSet, and retrieve data from the Authors table.
ds = New DataSet
da.FillSchema(ds, SchemaType.Source)
da.Fill(ds)
This cleared the information and allowed me to assign a new value. My subroutines serve double duty by assigning two query strings and then using an optional boolean to determine which version to use.
Dim sSelCmd As String = "SELECT * FROM Table WHERE Coloumn= 'b'"
Dim sSelAllCmd As String = "SELECT * FROM Table"
Private Sub GetData(Optional ByVal GetAll As Boolean = False)
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
And that leads into the code above! Thanks for the help. Some of your concepts got my thoughts turning in the right direction and motivated me to clean up my code into a much more readable form.