I have this code to load chart in Windows form program. It is placed in button click event handler. When I click the button first time chart is displayed OK. But on second click it will give me error "A chart element with the name 'Series1' could not be found in the 'SeriesCollection'." please see in code.
I'm new to VB not to mention charts and cannot figure out how to fix that so I can click the button any time(s) to reload the chart. Thanks a lot for any advice.
Dim pp As String = "J:\UCP\ApplicationsProgramming\MainDB.accdb"
Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pp & ";Persist Security Info=False;"
Dim tblFields As String = "SELECT Type, COUNT([Zone]) as CountZone FROM Faults GROUP BY Type "
Dim conn As New OleDbConnection(strConn)
Dim oCmd As New OleDbCommand(tblFields, conn)
Dim oData As New OleDbDataAdapter(tblFields, conn)
Dim ds As New DataSet
conn.Open()
oData.Fill(ds, "Faults")
conn.Close()
'''''''''''''''''''''''''''''
'~~> SET DATA SOURCE <~~'
'''''''''''''''''''''''''''''
Chart1.DataSource = ds.Tables("Faults")
''''''''''''''''''''''''''''''''
'~~> WORKING WITH CHARTAREA <~~'
''''''''''''''''''''''''''''''''
Dim CArea As ChartArea = Chart1.ChartAreas(0)
CArea.BackColor = Color.White
CArea.ShadowColor = Color.Red
CArea.Area3DStyle.Enable3D = True
'~~> Formatting X Axis
CArea.AxisX.MajorGrid.Enabled = False
CArea.AxisX.LabelStyle.Font = New System.Drawing.Font("Arial", _
10.0F, System.Drawing.FontStyle.Italic)
'~~> Formatting Y Axis
CArea.AxisY.MajorGrid.Enabled = False
CArea.AxisY.LabelStyle.Format = ""
CArea.AxisY.Interval = 0.1
''''''''''''''''''''''''''''
'~~> WORKING WITH TITLE <~~'
''''''''''''''''''''''''''''
'~~> Adding a Title
Dim T As Title = Chart1.Titles.Add("Fault Types")
'~~> Formatting the Title
With T
.ForeColor = Color.Black
.BackColor = Color.White
'~~> Setting Font, Font Size and Bold/Italicizing
.Font = New System.Drawing.Font("Arial", 11.0F, System.Drawing.FontStyle.Bold)
.BorderColor = Color.Black
.BorderDashStyle = ChartDashStyle.NotSet
End With
'''''''''''''''''''''''''''''
'~~> WORKING WITH SERIES <~~'
'''''''''''''''''''''''''''''
////// NEXT LINE WILL GIVE FOLLoWING ERROR:
////// "A chart element with the name 'Series1' could not be found in the 'SeriesCollection'." //////////
Dim Series1 As Series = Chart1.Series("Series1") <<<<<<<<<<
'~~> Setting the series Name
Series1.Name = "Fault Types"
'~~> Assigning values to X and Y Axis
Chart1.Series(Series1.Name).XValueMember = "Type"
Chart1.Series(Series1.Name).YValueMembers = "CountZone"
'~~> Setting Font, Font Size and Bold
Chart1.Series(Series1.Name).Font = New System.Drawing.Font("Arial", 10.0F, System.Drawing.FontStyle.Bold)
'~~> Setting Value Type
Chart1.Series(Series1.Name).YValueType = ChartValueType.Double
'~~> Setting the Chart Type for Display
'Chart1.Series(Series1.Name).ChartType = SeriesChartType.Radar
Chart1.Series(Series1.Name).ChartType = SeriesChartType.Pie
'~~> Display Data Labels
Chart1.Series(Series1.Name).IsValueShownAsLabel = True
'~~> Setting label's Fore Color
Chart1.Series(Series1.Name).LabelForeColor = Color.FloralWhite
'~~> Setting label's Format to %age
Chart1.Series(Series1.Name).LabelFormat = "" '"0.0%"
'~~> Setting the location for the chart
Chart1.Size = New System.Drawing.Size(865, 350)
The line Series1.Name = "Fault Types" changes the serie's name.
So, upon click, the next call to Dim Series1 As Series = Chart1.Series("Series1") will fail.
If you use only one serie, you should try Dim Series1 As Series = Chart1.Series(0)
Related
I have what on the face of it seems a pretty simple requirement, I need an unbound combobox column to hold an option list of 'Yes' and 'No'. In combobox parlance Yes and No are the DisplayMembers corresponding to ValueMembers 1 and 0 respectively which in turn are the values held in the field of the database table. I use bound combobox columns in the application extensively and am very familiar with building them, but can't for the hell of me work out how to incorporate this simple list functionality in the datagridview application. Could somebody please put me out of my misery with some sample code.
Thanks for your feedback Plutonix. The DGV is bound to an underlying table. Hopefully, the following code should give you some idea of what I am attempting to acheive. The code specifically relevant to this post is in the call to PopulateUnboundComboBox(comboBoxCol, {"Yes", "No"}).
Private Sub GetData()
Const procName As String = "GetData()"
Dim myValue As String = ""
Dim myDataSource As Integer = 0
Try
'First clear the existing grid
With Me.uxGrid
If .ColumnCount > 0 Then
'clear the grid
ClearGrid(Me.uxGrid)
End If
End With
_Logger.SendLog(Me.Name & "." & procName & " - Fetching device data.", NLog.LogLevel.Trace)
'Get the data from the database
If Not _dataSourceID = 0 Then
_sqlStatement = "SELECT ID, TEXT, CATEGORY, MOUNTING, DATASOURCEID, TANALYSIS" & _
" FROM P_TBL_DEVICE WHERE DATASOURCEID = " & _dataSourceID
_criteria = "WHERE DATASOURCEID = " & _dataSourceID
Else
_sqlStatement = ""
_criteria = ""
End If
_myDeviceMngr = New DeviceManager(_currentDB, _userName, _myPwd)
'Now get the latest data
_myDataSet = _myDeviceMngr.GetData(_sqlStatement)
_Logger.SendLog(Me.Name & "." & procName & " - Device data fetch completed.", NLog.LogLevel.Trace)
'Update the display
Call BuildGrid(_myDataSet, uxGrid)
Catch ex As Exception
Beep()
MsgBox(ex.Message, MsgBoxStyle.Exclamation, System.Windows.Forms.Application.ProductName)
_Logger.SendLog(ex.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, ex)
Finally
Call System.GC.Collect()
End Try
End Sub
Private Sub BuildGrid(ByVal myDataSet As DataSet, ByVal myGrid As DataGridView)
Dim myTable As New System.Data.DataTable
Dim myColCount As Integer
Dim comboBoxCol As DataGridViewComboBoxColumn
Dim readOnlyCellStyle As New DataGridViewCellStyle
Dim textBoxCol As DataGridViewTextBoxColumn
Dim gridObject As Object = Nothing
Const procName As String = "BuildGrid"
readOnlyCellStyle.ForeColor = Color.Gray
Try
_Logger.SendLog(Me.Name & "." & procName & " - Building device data grid.", NLog.LogLevel.Trace, Nothing)
myTable = myDataSet.Tables(0)
With myGrid
'Now add the columns to the grid
Dim column As System.Data.DataColumn
For Each column In myDataSet.Tables(0).Columns
'We dont want to include the changedon and changedby fields in the grid build
If column.ColumnName.IndexOf("CHANGED") = -1 Then
Select Case column.ColumnName
Case "DATASOURCEID"
gridObject = New Object
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
PopulateScadaSourceComboBoxCol(comboBoxCol)
comboBoxCol.DataPropertyName = "DATASOURCEID"
comboBoxCol.HeaderText = "SCADA SOURCE"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
Case "TEXT"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = column.ColumnName.Replace("TEXT", "DEVICE")
gridObject.name = column.ColumnName.Replace("TEXT", "DEVICE")
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "CATEGORY"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "CATEGORY"
gridObject.name = "CATEGORY"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "MOUNTING"
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "MOUNTING"
gridObject.name = "MOUNTING"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
Case "TANALYSIS"
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
PopulateUnboundComboBox(comboBoxCol, {"Yes", "No"})
comboBoxCol.DataPropertyName = "TANALYSIS"
comboBoxCol.HeaderText = "TELECONTROL ANALYSIS"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
Case Else
textBoxCol = New DataGridViewTextBoxColumn
gridObject = textBoxCol
'Now add the columns to the grid
gridObject.DataPropertyName = column.ColumnName.ToString
gridObject.HeaderText = "ID"
gridObject.name = "ID"
gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
End Select
'Now add the textbox columns to the grid
'gridObject.DataPropertyName = column.ColumnName.ToString
'gridObject.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
.Columns.Add(gridObject)
End If
Next
'Set grid default styles/values
.Font = New System.Drawing.Font("Arial", 10, FontStyle.Regular)
.AllowUserToResizeColumns = True
.AllowUserToResizeRows = True
.AllowUserToAddRows = True
.ReadOnly = True
.AutoResizeRows()
.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
'Now bind the datatable to the DGV datasource property
.DataSource = myTable
End With
_Logger.SendLog(Me.Name & "." & procName & " - Building of device data grid has been completed.", NLog.LogLevel.Trace, Nothing)
Catch ex As Exception
Throw
Finally
textBoxCol = Nothing
comboBoxCol = Nothing
readOnlyCellStyle = Nothing
GC.Collect()
End Try
End Sub
Private Sub PopulateUnboundComboBox(ByVal comboBoxCol As DataGridViewComboBoxColumn, byval valList() as string)
comboBoxCol.Name = "TANALYSIS"
comboBoxCol.DataSource = valList
comboBoxCol.ValueMember = ???
comboBoxCol.DisplayMember = ???
End Sub
EDITED//
Ok, I've made some progress and seem to have almost solved my issue. The one remaining bug is that the column in the DGV is displaying the 'ValueMember' (1 or 0) rather than the 'DisplayMember' (Yes or No). I've checked the valuemember and displaymember properties in the comboboxcolumn definition and and they appear to be set correctly. Here is the associated code:
Excerpt from original code posting listed above
...
Case "TANALYSIS"
gridObject = New Object
comboBoxCol = New DataGridViewComboBoxColumn
'First create the comboboxcolumn for the column
'Populate combobox
Dim item As New CBOItem
Dim itemList As New CBOItemList
item.ValueMember = 0
item.DisplayMember = "No"
itemList.Add(item)
item = New CBOItem
item.ValueMember = 1
item.DisplayMember = "Yes"
itemList.Add(item)
PopulateComboBox(comboBoxCol, itemList)
comboBoxCol.DataPropertyName = "TANALYSIS"
comboBoxCol.HeaderText = "TELECONTROL ANALYSIS"
comboBoxCol.AutoSizeMode = DataGridViewAutoSizeColumnsMode.AllCells
comboBoxCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
gridObject = comboBoxCol
...
Private Sub PopulateComboBox(ByRef comboBoxCol As DataGridViewComboBoxColumn, ByVal itemList As CBOItemList)
Dim tbl As DataTable = New DataTable
Dim row As DataRow
tbl.Columns.Add("ValueMember")
tbl.Columns.Add("DisplayMember")
row = tbl.NewRow
row.Item("ValueMember") = itemList(0).ValueMember
row.Item("DisplayMember") = itemList(0).DisplayMember
tbl.Rows.Add(row)
row = tbl.NewRow
row.Item("ValueMember") = itemList(1).ValueMember
row.Item("DisplayMember") = itemList(1).DisplayMember
tbl.Rows.Add(row)
comboBoxCol.ValueMember = tbl.Columns("ValueMember").ToString
comboBoxCol.DisplayMember = tbl.Columns("DisplayMember").ToString
comboBoxCol.DataSource = tbl
End Sub
Kind Regards
Paul J.
i have chart and i want fill it by searching between 2 dates ( my database is MS Access 2003 and i am using Vb.net Forms )
the error in SQL statment and the image link down shows the error
my code is
Try
Dim MyStringDate1 As Date = CDate(DateTimePicker1.Value.Date)
Dim MyStringDate2 As Date = CDate(DateTimePicker2.Value.Date)
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & Application.StartupPath & "\LIBRARY.mdb"
con.Open()
sql = "select CATEGORY , COUNT(CATEGORY)as CatStac from tblRentals where dateIssued between #" & MyStringDate1 & "# AND #" & MyStringDate2 & "# from tblRentals GROUP BY CATEGORY"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "tblRentals")
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
MsgBox(" SQL OR CONNECTION ERROR ")
End Try
Try
Dim T As Title = Chart1.Titles.Add("CATEGORY STACS FOR LIBRARY")
'~~> Formatting the Title
With T
.ForeColor = Color.Black '~~> Changing the Fore Color of the Title
.BackColor = Color.Coral '~~> Changing the Back Color of the Title
'~~> Setting Font, Font Size and Bold/Italicizing
.Font = New System.Drawing.Font("Times New Roman", 11.0F, System.Drawing.FontStyle.Bold)
.Font = New System.Drawing.Font("Times New Roman", 11.0F, System.Drawing.FontStyle.Underline)
.BorderColor = Color.Black '~~> Changing the Border Color of the Title
.BorderDashStyle = ChartDashStyle.DashDotDot '~~> Changing the Border Dash Style of the Title
End With
Chart1.DataSource = ds.Tables("tblRentals")
Dim Series1 As Series = Chart1.Series("Series1")
Series1.Name = "CATEGORY STACS"
Chart1.Series(Series1.Name).ChartType = SeriesChartType.Pie
' Chart1.Series(Series1.Name).LabelFormat = "0"
Chart1.Series(Series1.Name).IsValueShownAsLabel = True
Chart1.Series(Series1.Name).XValueMember = "CATEGORY"
Chart1.Series(Series1.Name).YValueMembers = "CatStac"
Dim LG As Legend = Chart1.Legends(0)
'~~> Changing the Back Color of the Legend
LG.BackColor = Color.Wheat
'~~> Changing the Fore Color of the Legend
LG.ForeColor = Color.DarkSlateBlue
'~~> Setting Font, Font Size and Bold
LG.Font = New System.Drawing.Font("Times New Roman", 11.0F, System.Drawing.FontStyle.Bold)
'~~> Assigning a title for the legend
LG.Title = "Legend"
Chart1.Size = New System.Drawing.Size(500, 500)
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("CHART ERROR ")
End Try
http://s17.postimg.org/wqkde2fjj/image.png
try change the select like this :
sql = "select CATEGORY , COUNT(CATEGORY)as CatStac from tblRentals where dateIssued > #" & MyStringDate1 & "# AND dateIssued < #" & MyStringDate2 & "# GROUP BY CATEGORY"
Add this to your code to bind your dataSet to chart :
'Set chart data source
chart1.DataSource = ds
'Set series members names for the X and Y values
chart1.Series("Series 1").XValueMember = "col1"
chart1.Series("Series 1").YValueMembers = "col2"
'Data bind to the selected data source
chart1.DataBind()
I am trying to create a datagridview that will automatically format the numbers that a user enters. My datagridview is not linked to a datasource, it is built programmatically like so:
Private Sub FormatGridView()
Dim ILNumColumn As New DataGridViewTextBoxColumn
Dim ArtNumColumn As New DataGridViewTextBoxColumn
Dim DescColumn As New DataGridViewTextBoxColumn
'Header text
ILNumColumn.HeaderText = "# IL"
ArtNumColumn.HeaderText = "# Articles"
DescColumn.HeaderText = "Description"
'Wrap
DescColumn.DefaultCellStyle.WrapMode = DataGridViewTriState.True
'Widths
ILNumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
ArtNumColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
DescColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
'Add columns
dgvArticles.Columns.Add(ILNumColumn)
dgvArticles.Columns.Add(ArtNumColumn)
dgvArticles.Columns.Add(DescColumn)
End Sub
Is there a way to make the IlNumColumn always be in the format below in the green circle?
Number format
'Formatting
ILNumColumn.DefaultCellStyle.Format = "000"
This will make all the numbers in the IlNumColumn in a "001" format.
i wrote program in vb.net. in my page, i have 3 textbox. in Txt_CardBarcode_TextChanged ,i wrote this codes:
Try
Dim stream_CardBarcode As System.IO.MemoryStream = New System.IO.MemoryStream
Dim cls As New Cls_Barcode
Dim pic_CardBarcode As System.Drawing.Image = Nothing
cls.btnEncode(pic_CardBarcode, Txt_CardBarcode.Text.Trim)
pic_CardBarcode.Save(stream_CardBarcode, System.Drawing.Imaging.ImageFormat.Png)
Dim f_cardBarcode As IO.FileStream = _
New IO.FileStream("C:\fafa.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
Dim b_cardBarcode As Byte() = stream_CardBarcode.ToArray
f_cardBarcode.Write(b_cardBarcode, 0, b_cardBarcode.Length)
f_cardBarcode.Close()
Dim ds As DS_Test
ds = New DS_Test
Dim Val_LabelBarcode() = {stream_CardBarcode.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(2).Rows.Add(Val_LabelBarcode)
crp_CardBarcode.SetDataSource(ds.Tables(2))
Dim frm_CrpCardBarcode As New Frm_RepCardBarcode
frm_CrpCardBarcode.CrystalReportViewer1.ReportSource = crp_CardBarcode
GVSimInfo.DataSource = ds.Tables(2)
ds.Tables(2).Rows.Add(1)
GVSimInfo.Rows(GVSimInfo.Rows.Count - 1).Cells(0).Value = True
ds.Tables(2).Rows(0).Item(0) = True
ds.Tables(2).Rows(0).Item(1) = ""
ds.Tables(2).Rows(0).Item(2) = Txt_ICCID.Text
ds.Tables(2).Rows(0).Item(3) = ""
ds.Tables(2).Rows(0).Item(4) = ""
now, in run time, after filling 3textbox, new row add to gridview , but when user want to more than filling textboxes, new row in grid view replace on old row!!!
how to set new row add to grid view , instead of replace old row?
in my dataset, i put 3tables. tables(2) has 2 columns that save image barcode with byte array data type, but in my gridview ,i have 5 columns.
in run time give me error dialog,it is images from it:
If your DGV is not bound to any data Source:
GVSimInfo.Rows.Add(1);
If your DGV is bound to some Data Source then :
ds.Tables(2).Rows.Add(1)
Add this code after your last text box is filled and new row is needed.
to set the values you can use :
ds.Tables(2).Rows(0).Item("Column_number") = "your text"
Try
Dim stream_CardBarcode As System.IO.MemoryStream = New System.IO.MemoryStream
Dim cls As New Cls_Barcode
Dim pic_CardBarcode As System.Drawing.Image = Nothing
cls.btnEncode(pic_CardBarcode, Txt_CardBarcode.Text.Trim)
pic_CardBarcode.Save(stream_CardBarcode, System.Drawing.Imaging.ImageFormat.Png)
Dim f_cardBarcode As IO.FileStream = _
New IO.FileStream("C:\fafa.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
Dim b_cardBarcode As Byte() = stream_CardBarcode.ToArray
f_cardBarcode.Write(b_cardBarcode, 0, b_cardBarcode.Length)
f_cardBarcode.Close()
Dim ds As DS_Test
ds = New DS_Test
Dim Val_LabelBarcode() = {stream_CardBarcode.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(2).Rows.Add(Val_LabelBarcode)
crp_CardBarcode.SetDataSource(ds.Tables(2))
Dim frm_CrpCardBarcode As New Frm_RepCardBarcode
frm_CrpCardBarcode.CrystalReportViewer1.ReportSource = crp_CardBarcode
ds.Tables(2).Rows.Add(1)
GVSimInfo.Rows(GVSimInfo.Rows.Count - 1).Cells(0).Value = True
ds.Tables(2).Rows(0).Item(0) = True
ds.Tables(2).Rows(0).Item(1) = ""
ds.Tables(2).Rows(0).Item(2) = Txt_ICCID.Text
ds.Tables(2).Rows(0).Item(3) = ""
ds.Tables(2).Rows(0).Item(4) = ""
GVSimInfo.DataSource = ds.Tables(2) <-------
I am using the MS Chart control (version 3.5.0).
I have added it by using the designer (drag and drop). I removed the default "Series1" from the Properties -> Series -> Collection so that the chart contains no data.
I am adding the data at runtime based on a canned query to a SQLite DB. Like so:
Dim SQL As String = "SELECT * FROM ageLength ORDER BY month"
Dim cmd As New SQLiteCommand(SQL)
Dim SqLiteConnection1 As SQLiteConnection = New SQLiteConnection()
SqLiteConnection1.ConnectionString = "Data Source=" & My.Application.Info.DirectoryPath & "\Data\UserData.db3;"
cmd.Connection = SqLiteConnection1
Dim da As New SQLiteDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "ageLength")
Dim Series1 As Series = New Series()
Dim Series2 As Series = New Series()
Series1.Name = "Pcnt2nd"
Series1.ChartType = SeriesChartType.Spline
Series2.Name = "Pcnt98th"
Series2.ChartType = SeriesChartType.Spline
Chart1.Series.Add("Pcnt2nd")
Chart1.Series.Add("Pcnt98th")
Chart1.Series("Pcnt2nd").XValueMember = "month"
Chart1.Series("Pcnt2nd").YValueMembers = "Pcnt2nd"
Chart1.Series("Pcnt98th").XValueMember = "month"
Chart1.Series("Pcnt98th").YValueMembers = "Pcnt98th"
Chart1.DataSource = ds.Tables(0)
The data is displayed on the Chart, however, it is a Bar type graph. I set it to use the Spline type for both series. I am not sure what I missed. Any input is greatly appreciated.
After doing a lot more messing around I found the solution:
I remove these 2 lines:
Series1.ChartType = SeriesChartType.Spline
Series2.ChartType = SeriesChartType.Spline
And then I add these 2 lines:
Chart1.Series("Pcnt2nd").ChartType = DataVisualization.Charting.SeriesChartType.Line
Chart1.Series("Pcnt98th").ChartType = DataVisualization.Charting.SeriesChartType.Line
Not sure why that is...but there you have it.