Datagridview Number Format - vb.net

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.

Related

Remove the time in Datagridview and when exported to PDF

Please help me guys!
I want the time in Date_Purchased(date) to be removed in datagridview. Because whenever I exported the datagrid in PDF, it has the date and time in it. I only want the date and remove the time especially when exported to PDf.
Here's the sample piece of code.
Public Sub NewInventory()
Dim NI as SqlCommand =con.CreateCommand
NI.CommandText = "Insert into Items_table(Room_ID, PC_Number, Item_Name, Date_Purhased) VALUES (#Room_ID,#PC_Number, #Item_Name, #Date_Purchased);"
NI.Parameters.AddWithValue("#Room_ID", Room_ID)
NI.Parameters.AddWithValue("#PC_Number", PC_Number)
NI.Parameters.AddWithValue("#Item_Name", Item_Name)
NI.Parameters.AddWithValue("#Date_Purchased", DatePurchasedDTP.Value)
NI.ExecuteNonQuery()
MessageBox.Show("New item created.")
End Sub
//for DataGridView
Public Sub GetRoomItems(RoomID As String)
Dim getItems As String = "Select Item_ID, PC_Number,
Item_Name, Date_Purchased WHERE Room_ID=" + RoomID
Dim adapter As New SqlDataAdapter(getItems, connection)
Dim table As New DataTable()
adapter.Fill(table)
InventoryDataGrid.DataSource = table
End Sub
//For exporting to pdf
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
connection.Close()
connection.Open()
Dim pdfTable As New PdfPTable(ReportDataGridView.ColumnCount)
pdfTable.DefaultCell.Padding = 1
pdfTable.WidthPercentage = 100
pdfTable.DefaultCell.HorizontalAlignment = Element. ALIGN_CENTER
Dim ptable As New Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
For Each column As DataGridViewColumn in ReportDataGridView.Columns
Dim cell as new PdfPCell(New Phrase(New Chunk(column.HeaderText, ptable)))
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.FixedHeight = 30
pdfTable.AddCell(cell)
Next
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
Dim folderpath As String = "C:\PDFs\"
If Not Directory.Exists(folderpath) Then
Directory.CreateDirectory(folderpath)
End If
Using sfd as New SaveFileDialog()
sfd.ShowDialog()
sfd.OverWritePrompt = True
sfd.Title =" Save As"
sfd.AddExtension = True
sfd.DefaultExt = ".pdf"
Using stream As New FileStream(sfd.FileName & ".pdf",
FileMode.Create)
Dim pdfdoc As New Document (PageSize.LETTER, 36.0F, 36.0F,36.0F,36.0F)
PdfWriter.GetInstance(pdfdoc.stream)
pdfdoc.Open()
pdfdoc.Add(pdfTable)
pdfdoc.Close()
stream.Close()
If File.Exists("path") Then
File.AppendAllText("path", "contents")
End If
pdfdoc.Close()
stream.Close()
End Using
End Using
End Sub
If you would ask me what's the data type of Date_Purchased, it is date. I used date not datetime. And still confused why the time is still in pdf whenever I exported it.
Please help me! Thank you so much
In .NET a Date still has a time component, it's just set to midnight (e.g. 12:00:00). You can read about this here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.8
A new object with the same date as this instance, and the time value
set to 00:00:00 midnight (00:00:00).
If you want to display a Date as a string with only the date, you can use Date.ToString() and specify a format which omits the time such as Date.ToString("dd/MM/yyyy"). Alternatively you can use Date.ToShortDateString() which does this but uses the current culture short date string format.
More info here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.8
In your code you are doing this loop:
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
If you change this to use the underlying DataTable instead of the DataGridView itself you can use the DataColumn.DataType to check when you're using a date:
For Each row as DataRow In DataTable.Rows
For Each item In row.ItemArray
If item.GetType Is GetType("System.DateTime") Then
pdfTable.AddCell(item.ToString("dd/MM/yyyy"))
Else
pdfTable.AddCell(item.Value.ToString)
End If
Next
Next
I'm a bit rusty on the specifc syntax but you should be able to work it out from there.

DataGridView Yes No ComboBox Column

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.

vb.net Error after Adding typed text item from datagridViewComboboxColumn into database

Basically, I wan't the user to be able to type into datagridViewComboboxColumn
and if there is no match it will automatically save the text into the database, update the BindingSource and select the item.
Heres what I have so far.
The bindingsource:
With acctTitleCombo6
.AutoComplete = True
Try
.DataSource = ds4
.DisplayMember = "desc_description"
.ValueMember = "desc_id"
.DataPropertyName = "desc_id"
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End With
Changing combobox style to dropdown in EditingControlShowing:
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
If (DataGridView2.CurrentCellAddress.X = comboBoxColumn.DisplayIndex) Then
Dim cb As ComboBox = TryCast(e.Control, ComboBox)
If (cb IsNot Nothing) Then
cb.DropDownStyle = ComboBoxStyle.DropDown
End If
End If
Checking if typed text is already in the source item (CellValidating event).
Dim comboBoxColumn As DataGridViewComboBoxColumn = DataGridView2.Columns(0)
cs2.Open()
Dim comm, comm2, comm3 As New MySqlCommand
comm.Connection = cs2
Dim msgAddDesc As String = "Your description is currently not in the list." & vbNewLine & _
"Would you like to add '"
If (e.ColumnIndex = comboBoxColumn.DisplayIndex) And Not String.IsNullOrWhiteSpace(e.FormattedValue) Then
Dim itemIE As IEnumerator = comboBoxColumn.Items.GetEnumerator
itemIE.Reset()
Dim thisItem As DataRowView
Dim exist As Boolean = False
While itemIE.MoveNext()
thisItem = CType(itemIE.Current(), DataRowView)
Dim valueMember As Object = thisItem.Row.ItemArray(0)
Dim displayMember As Object = thisItem.Row.ItemArray(1)
If displayMember.ToString = e.FormattedValue Then
exist = True
End If
End While
If exist = False Then
If MessageBox.Show(msgAddDesc & e.FormattedValue & "' to the list?", "Does not exist", _
MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
comm.CommandText = "INSERT INTO ref_description(desc_description) " & _
"VALUES(#description)"
With comm.Parameters
.Add("#description", MySqlDbType.VarChar).Value = e.FormattedValue
End With
comm.ExecuteNonQuery()
comm.Parameters.Clear()
End If
End If
End If
cs2.Close()
Now, whenever I add a new item into the database, this error comes up but sometimes it doesn't:
The following exception occurred in the DataGridView:
System.FormatException: Value '' cannot be converted to type 'System.String'.
at System.Windows.Forms.DataGridViewComboBoxCell.ParseFormattedValue(Object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
at System.Windows.Forms.DataGridView.PushFormattedValue(DataGridViewCell& dataGridViewCurrentCell, Object formattedValue, Exception& exception)
Another question is, how can I update the combobox after I add the new item into the database, then I also want to automatically select the new item when the user press enter or tab (only when there's a new item added into the database).
I'm not sure, if I can help. However, the error comes from DataGridView, not combo. I suspect, that you update the datagridview at the same time (as you try to update the combo), which will not work. I think you need to finish cell editing first (incl. validation), then you can update the datagridview. I'd try to move it to CellEndEdit() event.
how can I update the combobox: I don't see the code, how you load the ComboBox in the first place.
Usually, you just update related dataset and re-assign it to ComboBox.DataSource, or you can use databinding (no need to update then, but one usually uses it if in need of more binding features).
Private Sub LoadUpdateSubListCombo()
Dim cmdText as String
cmdText = "SELECT ID,SubName FROM SubmarinesTable "
Dim ds as DataSet
ds = MyDataAccessLayer.GetQueryResults(cmdText)
Dim SubDT As DataTable = ds.Tables(0).DefaultView
cb3.DataSource = SubDT
cb3.ValueMember = "ID"
cb3.DisplayMember = "SubName"
End Sub
...where cb3 is a ComboBox...

Set selectedindex for comboboxcell in datagridview vb.net

I am trying to set the selectedindex for my datagridviewcomboboxcell through cellvaluechanged event,i.e when i change some value in my datagrid row, this column should get automatically changed. here's the code.
Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Try
If Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString <> Nothing Then
Me.DataGridView1("unit_code", e.RowIndex).Value = "1"
MsgBox(Me.DataGridView1.Rows(e.RowIndex).Cells(6).Value)
End If
Else
Exit Sub
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
my datagridview is bound to dataset. Searched many sites and did all research, got the above solution where we need to set the valuemember to .value part. Even after doing that it givessystem.formatexception:datagridviewcomboboxcell value is not valid.
Please help me.
[EDIT]
table structure
unit_code descp
0 -
1 nos
2 kgs
3 gms
[EDIT 2]
query = "select Switch(qty=0,'2',qty<=rcvd_qty,'1',rcvd_qty=0,'2',qty>rcvd_qty,'3') as Status,item_type,catalogue,name,pd.rate,qty,pd.unit_code" _
& " from pur_det pd,itemhead th where pd.item_code=th.itemcode and order_no=0 order by catalogue"
adap1 = New OleDbDataAdapter(query, conn)
Dim saldet As New DataSet
adap1.Fill(saldet, "puritems")
Me.DataGridView1.DataSource = saldet.Tables(0)
DataGridView1.Columns.Item(0).HeaderText = "STATUS"
DataGridView1.Columns.Item(0).Width = 68
DataGridView1.Columns.Item(1).HeaderText = "TYPE"
DataGridView1.Columns.Item(1).Width = 60
DataGridView1.Columns.Item(2).HeaderText = "CATALOGUE"
DataGridView1.Columns.Item(2).Width = 140
DataGridView1.Columns.Item(3).HeaderText = "DESCRIPTION"
DataGridView1.Columns.Item(3).Width = 300
DataGridView1.Columns.Item(4).HeaderText = "RATE"
DataGridView1.Columns.Item(4).Width = 60
DataGridView1.Columns.Item(5).HeaderText = "QUANTITY"
DataGridView1.Columns.Item(5).Width = 84
DataGridView1.Columns.Item(6).HeaderText = "UNIT" ' this column is removed below because it only had primary key values of this table("unitmast").
DataGridView1.Columns.Item(6).Width = 70
adap1 = New OleDbDataAdapter("select * from unitmast order by unitcode ASC", conn)
Dim unitc As New DataSet
adap1.Fill(unitc, "unitmast")
Me.DataGridView1.Columns.RemoveAt(6) 'here the same is added with display member to view its actual value
Dim uncol As New DataGridViewComboBoxColumn
With uncol
.Name = "unit_code"
.DataPropertyName = "unit_code"
.DataSource = unitc.Tables(0)
.ValueMember = "unitcode"
.DisplayMember = "desc"
.HeaderText = "UNIT"
.FlatStyle = FlatStyle.Flat
.DropDownWidth = 160
.Width = 70
End With
Me.DataGridView1.Columns.Insert(6, uncol)
A DataGridViewComboBoxCell has no SelectedIndex or SelectedValue property.
You can set the value directly like this:
CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell).Value = "your value string"
Or using the index of the items collection: (this works only if you have not set ValueMember and DisplayMember properties)
Dim combo As DataGridViewComboBoxCell
combo = CType(Me.DataGridView1("unit_code", e.RowIndex), DataGridViewComboBoxCell)
combo.Value = combo.Items('your index')
You can also check a value for nothing like this:
If Not Me.DataGridView1.Rows(e.RowIndex).Cells(2).Value Is Nothing Then
'Your code
End If
I Write and Test that Code For You Good Luck:
Dim Dt As New DataTable
Sub CreateDT()
Dt.Columns.Add("Col1")
Dt.Columns.Add("Col2")
Dt.Rows.Add(New Object(1) {"1", "A"})
Dt.Rows.Add(New Object(1) {"2", "B"})
Dt.Rows.Add(New Object(1) {"3", "C"})
End Sub
Private Sub ChildRibbonForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CreateDT()
'
'Dim CellCol As DataGridViewComboBoxColumn = CType(DataGridView1.Columns(0), DataGridViewComboBoxColumn)
Dim CellCol As New DataGridViewComboBoxColumn
CellCol.Items.Add("Test1")
CellCol.Items.Add("Test2")
CellCol.Items.Add("Test3")
Me.DataGridView1.DataSource = Dt
Me.DataGridView1.Columns.Insert(0, CellCol)
Dim CellBox As DataGridViewComboBoxCell = CType(DataGridView1.Rows(1).Cells(0), DataGridViewComboBoxCell)
'Select the Second Item
CellBox.Value = CellCol.Items(1)
End Sub
'Declare datatable
Dim cdt as new Datatable
'Add columns with types. It is important you specify the type for value member column
cdt.Columns.Add("vm", System.Type.GetType("System.Int32"))
cdt.Columns.Add("dm", System.Type.GetType("System.String"))
'Add items to table
cdt.Rows.Add
cdt.Rows(0).Item(0) = 1
cdt.Rows(0).Item(1) = "Red Cat"
cdt.Rows.Add
cdt.Rows(1).Item(0) = 2
cdt.Rows(1).Item(1) = "Black Cat"
'Add datasource to DataGridViewComboBoxColumn
Dim cc As DataGridViewComboBoxColumn
cc = datagridview1.Columns('colIndex')
cc.DataSource = cdt
cc.ValueMember = "vm"
cc.DisplayMember = "dm"
'Setting then selected value is thus:
Datagridview1.Rows('rowIndex').Cells('colIndex').Value = 2 '2 for black cat
This works for me

How to reload Chart in VB NET

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)