ComboBox Control within DatagridView - vb.net

I want to use DGV as a table to take User’s inputs. And in few columns, I want User to select values from a collection hence I decided to use Comboboxcontrol. I selected a standard DGV ("DGV2") and a standard Combobox ("CBTest") as tools. And I programmed this Combo to appear on Columnindex 2 (when user enters the particular cell, Combo box pops-up). User can select from the combo items (Drop-Down-List) and after selection clicked done, curser moves to next column.
Now there is problems with UP/DOWN Keys when control is in cell having COMBO-BOX-
I am not able to control behavior of UP /DOWN Keys when user enters the Cell having COMBO Control.
Sometime with up-down keys cursor moves between Combobox items and sometimes it jumps in other rows.
I am a beginner so any hint and help will be useful.
Code I used -
Public Class frmSIDDGV
Dim nCol As Integer = 0
Dim nRow As Integer = 0
Private Sub frmSIDDGV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With DGV2
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
.AutoResizeColumns()
.RowTemplate.Height = 40
.RowHeadersVisible = False
End With
DGV2.ColumnCount = 5
With DGV2
.Columns(0).Name = "Item"
.Columns(1).Name = "MRP"
.Columns(2).Name = "Qty"
.Columns(3).Name = "Unit"
.Columns(4).Name = "Amount"
End With
DGV2.Rows.Add()
DGV2(0, 0).Value = 1
End Sub
Private Sub DGV2_KeyUp(sender As Object, e As KeyEventArgs) Handles DGV2.KeyUp
If e.KeyCode = Keys.Enter Then
If ActiveControl.Name <> "CBTest" Then
If nCol = DGV2.ColumnCount - 1 Then
DGV2.Rows.Add()
DGV2.CurrentCell = DGV2(0, nRow + 1)
Else
DGV2.CurrentCell = DGV2(nCol + 1, nRow)
End If
End If
ElseIf e.KeyCode = Keys.Escape Then
If ActiveControl.Name = "CBTest" Then
CBTest.SelectedIndex = 0 : CBTest.Visible = False
DGV2.CurrentCell = DGV2(nCol, nRow)
DGV2.Focus()
End If
End If
End Sub
Private Sub DGV2_CurrentCellChanged(sender As Object, e As EventArgs) Handles DGV2.CurrentCellChanged
Try
nCol = DGV2.CurrentCell.ColumnIndex
nRow = DGV2.CurrentCell.RowIndex
Catch ex As Exception
nCol = 0
nRow = 0
End Try
End Sub
Private Sub DGV2_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGV2.CellEnter
Select Case e.ColumnIndex
Case 2 ' User entered in Cell name "Item"
DGV2.Controls.Add(CBTest)
'DGV2.BeginEdit(True)
Dim oRectangle = DGV2.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True)
CBTest.Size = New Size(oRectangle.Width, oRectangle.Height)
CBTest.Location = New Point(oRectangle.X, oRectangle.Y)
CBTest.Visible = True
SendKeys.Send("{F4}")
CBTest.SelectedIndex = 0
CBTest.Capture = True
CBTest.Focus()
End Select
End Sub
Private Sub CBTest_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles CBTest.SelectionChangeCommitted
With DGV2
.Focus()
.Item(nCol, nRow).Value = Trim(CBTest.Text)
.CurrentCell = .Rows(.CurrentRow.Index).Cells(nCol + 1)
End With
CBTest.Visible = False
End Sub
End Class

Related

copy the data from unbound dgv to bound dgv

I have two dgv, the first dgv is unbound and the second is bound. I want to copy the data in every cell to the bound dgv in order to save it. I have button but when I click it it says "Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound."
Here is my code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For i As Integer = 0 To DataGridView1.Rows.Count() - 1 Step +1
Dim rowAlreadyExist As Boolean = False
Dim check As Boolean = DataGridView1.Rows(i).Cells(3).Value
Dim row As DataGridViewRow = DataGridView1.Rows(i)
If check = True Then
If Sales.SalesDataGridView.Rows.Count() > 0 Then
For j As Integer = 0 To Sales.SalesDataGridView.Rows.Count() - 1 Step +1
If row.Cells(0).Value.ToString() = Sales.SalesDataGridView.Rows(j).Cells(0).ToString() Then
rowAlreadyExist = True
Exit For
End If
Next
If rowAlreadyExist = False Then
Sales.SalesDataGridView.Rows.Add(row.Cells(0).Value.ToString(),
row.Cells(1).Value.ToString(),
row.Cells(2).Value.ToString(),
row.Cells(3).Value.ToString(),
row.Cells(4).Value)
End If
Else
Sales.SalesDataGridView.Rows.Add(row.Cells(0).Value.ToString(),
row.Cells(1).Value.ToString(),
row.Cells(2).Value.ToString(),
row.Cells(3).Value.ToString(),
row.Cells(4).Value)
End If
End If
Next

Datagridview (VB 2010) Readonly property for a column, "strange" behavior

I encountered a strange behavior with the following code on a datagridview in VB2010.
dgv is the name of the datagridview. In FormLoad, I wrote
Private Sub frmdataLog_Load(sender As Object, e As System.EventArgs) Handles Me.Load
dgv.ColumnCount = 5
dgv.Columns(0).Width = 27
Dim j As Integer
For j = 1 To 4
dgv.Columns(j).Width = 85
Next
dgv.Rows.Add(1)
dgv.Columns(0).HeaderText = "Sl No."
dgv.Columns(1).HeaderText = "Test Reading Nm"
dgv.Columns(2).HeaderText = "Standard Reading Nm"
dgv.Columns(3).HeaderText = "Error in Nm"
dgv.Columns(4).HeaderText = "% Uncertainty"
For j = 0 To 5
dgv.Columns(j).ReadOnly = True
dgv.Columns(j).SortMode = DataGridViewColumnSortMode.NotSortable
Next
dgv.Columns(1).ReadOnly = False
End Sub
I am expecting column(1) to be editable while all other columns will be uneditable.
But I found that even column(1) is also readonly!
But when I added the following code, the problem got solved:
Private Sub dgv_CellEnter(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellEnter
colVal = e.ColumnIndex
rowVal = e.RowIndex
If dgv.Columns(1).ReadOnly = True Then
dgv.Columns(1).ReadOnly = False
End If
End Sub
My question is why does the line dgv.Columns(1).ReadOnly = False not execute under Form load?

Select only one checkbox from multiple checkbox in a row from DataGridView

I'm using DataGridView with DataSource from TableAdapter and add 5 unbound columns with type DataGridViewCheckBoxColumn .
They are : "lima","empat","tiga","dua","satu"
What I need to do, in the same row when checkbox "lima" is selected, the rest checkboxes become unselected or only can select one checkbox in the same row
Here's what I wrote down in CellValueChanged event :
Private Sub DataGridView3_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView3.CellValueChanged
If DataGridView3.CurrentRow IsNot Nothing Then
Dim SelectedColumnName = DataGridView3.Columns(DataGridView3.CurrentCellValue.ColumnIndex).Name
If e.ColumnIndex = DataGridView3.Columns("lima").Index OrElse _
e.ColumnIndex = DataGridView3.Columns("empat").Index OrElse _
e.ColumnIndex = DataGridView3.Columns("tiga").Index OrElse _
e.ColumnIndex = DataGridView3.Columns("dua").Index OrElse _
e.ColumnIndex = DataGridView3.Columns("satu").Index Then
Dim Row = CType((CType(DataGridView3.DataSource.Current, DataRowView)).Row, DataRow)
If SelectedColumnName = "lima" Then
If DataGridView3.CurrentRowCellValue("lima") = "True" Then
Row.Item("empat") = False
Row.Item("tiga") = False
Row.Item("dua") = False
Row.Item("satu") = False
End If
'and so..on
ElseIf SelectedColumnName = "satu" Then
If DataGridView3.CurrentRowCellValue("satu") = "True" Then
Row.Item("lima") = False
Row.Item("empat") = False
Row.Item("tiga") = False
Row.Item("dua") = False
End If
End If
DataGridView3.CurrentCell = DataGridView3(e.ColumnIndex, e.RowIndex)
End If
End If
End Sub
And this is the functions for CurrentCell and CurrentRowCellValue in module
<System.Diagnostics.DebuggerStepThrough()> _
<Runtime.CompilerServices.Extension()> _
Function CurrentRowCellValue(ByVal sender As DataGridView, ByVal ColumnName As String) As String
Dim Result As String = ""
If Not sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value Is Nothing Then
Result = sender.Rows(sender.CurrentRow.Index).Cells(ColumnName).Value.ToString
End If
Return Result
End Function
<System.Diagnostics.DebuggerStepThrough()> _
<Runtime.CompilerServices.Extension()> _
Function CurrentCellValue(ByVal sender As DataGridView) As DataGridViewCell
Return sender(sender.Columns(sender.CurrentCell.ColumnIndex).Index, sender.CurrentRow.Index)
End Function
and this is from CurrentCellDirtyStateChanged event
Private Sub DataGridView3_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView3.CurrentCellDirtyStateChanged
If TypeOf DataGridView3.CurrentCell Is DataGridViewCheckBoxCell Then
DataGridView3.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
I already set the DataGridView's ReadOnly property to False. The problem is that I still can check all the checkboxes in the same row.
Can someone give advice of what I did wrong here ?
Thanks
Some tips:
See this link concerning CellValuechanged event when working with checkBoxs
If they are unbound columns, you can't change values via the DataSource.Current row: table has no definition for lima, empat, ...
This workaround (using CellContentClick) works for me (no need to extension methods and CurrentCellDirtyStateChanged event):
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView3.CellContentClick
Dim checkboxIndexes As New List(Of Integer)
checkboxIndexes.Add(DataGridView3.Columns("lima").Index)
checkboxIndexes.Add(DataGridView3.Columns("empat").Index)
checkboxIndexes.Add(DataGridView3.Columns("tiga").Index)
checkboxIndexes.Add(DataGridView3.Columns("dua").Index)
checkboxIndexes.Add(DataGridView3.Columns("satu").Index)
If checkboxIndexes.Contains(e.ColumnIndex) Then
'check for false value because event occurs before row is validated
If DataGridView3.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False Then
For Each index In checkboxIndexes
If index <> e.ColumnIndex Then
DataGridView3.Rows(e.RowIndex).Cells(index).Value = False
End If
Next
End If
End If
End Sub
I made an improve to the code added before in order to achieve my goals of checking checkboxes of the same row in different columns. It works for me.
Private Sub Grilla_CellClick(sender As Object, e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles Grilla.CellClick
Dim checkboxIndexes As New List(Of Integer)
checkboxIndexes.Add(Grilla.Columns("Select").Index)
checkboxIndexes.Add(Grilla.Columns("Select1").Index)
If checkboxIndexes.Contains(e.ColumnIndex) Then
'check for false value because event occurs before row is validated
If Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False Then
For Each index In checkboxIndexes
If index <> e.ColumnIndex Then
'Do nothing here
Else
If Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False Then
Grilla.Rows(e.RowIndex).Cells(index).Value = True
Else
Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False
End If
End If
Next
Else
If Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = True Then
For Each index In checkboxIndexes
If index <> e.ColumnIndex Then
'Do nothing here
Else
If Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False Then
Grilla.Rows(e.RowIndex).Cells(index).Value = True
Else
Grilla.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = False
End If
End If
Next
End If
End If
End If
Grilla.TableElement.Update(GridUINotifyAction.DataChanged)
End Sub

looking for a way to re enable labels without specifying which ones vb.net

I am looking for a way, if its even possible, to re enable a label without actually needing to use its label name?
I have a game with labels I am using as click able boxes. The first box becomes disabled after the click event occurs, I want after the second box is clicked to re enable that first box. Any Ideas? Here is the code for the first two box click events.
Edit: there will be 15 labels, 2 can be chosen at a time. The first will be disabled so that it can't be chosen a second time.
Private Sub lblMemory1_Click(sender As Object, e As EventArgs) Handles lblMemory1.Click
Dim intClickBox As Integer = 1
Dim intClickAnswer As Integer
intClickAnswer = GuessClick(intClickBox)
If blnActive = False Then
blnActive = True
whatClicked1 = intClickBox
lblMemory1.BackColor = Color.Green
lblMemory1.Text = intClickAnswer.ToString
lblMemory1.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory1.BackColor = Color.Cyan
lblMemory1.Text = "X"
lblMemory1.Enabled = False
End If
If blnActive = True Then
whatClicked2 = intClickBox
lblMemory1.BackColor = Color.Green
lblMemory1.Text = intClickAnswer.ToString
lblMemory1.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory1.BackColor = Color.Cyan
lblMemory1.Text = "X"
blnActive = False
End If
End Sub
Private Sub lblMemory2_Click(sender As Object, e As EventArgs) Handles lblMemory2.Click
Dim intClickBox As Integer = 2
Dim intClickAnswer As Integer
intClickAnswer = GuessClick(intClickBox)
If blnActive = False Then
blnActive = True
whatClicked1 = intClickBox
lblMemory2.BackColor = Color.Green
lblMemory2.Text = intClickAnswer.ToString
lblMemory2.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory2.BackColor = Color.Cyan
lblMemory2.Text = "X"
lblMemory2.Enabled = False
End If
If blnActive = True Then
whatClicked2 = intClickBox
lblMemory2.BackColor = Color.Green
lblMemory2.Text = intClickAnswer.ToString
lblMemory2.Refresh()
System.Threading.Thread.Sleep(2000)
lblMemory2.BackColor = Color.Cyan
lblMemory2.Text = "X"
blnActive = False
End If
End Sub
you can do something like
Public Sub game(sender As Object)
Dim lbl As Label = sender
If lbl.Enabled Then
For i = 0 To Me.Controls.Count - 1
Dim lbl2 As Label = Me.Controls(i)
If Not (lbl2.Enabled) Then
lbl2.Enabled = True
GoTo exitLoop
End If
Next
End If
exitLoop:
lbl.Enabled = False
End Sub
then in each label just call the game sub and pass sender like so...
Private Sub Label1_Click(sender As System.Object, e As System.EventArgs) Handles Label1.Click
game(sender)
End Sub
this will allow only 1 label to be diabled at any give time...
you can also (within the loops) use lbl and lbl2 to set the properties for each label.
if you use a var to save the name of the first textbox you can also specifically re-enable only that box...
let me know if you want the code for that too.

How would I add a progress bar to display on form button click that shows the progress of form2 load

I have a Start form with a "View Records" button. On the Records Form Load event I have the loop that populates a datagridview on the Records Form. What I want to do is show a progress bar next to the "View Records" button on the Start form that shows the progress of the datagridview on the Records form when the user clicks the "View Records" button. Then, once the datagridview loop is successfully completed I want to bring up the Records form (but still leave Start form open as parent form, so the "View Record" form would be brought up by a ShowDialog). I have the simple code to show the progress bar on "View Records" button click. I'm reading around to find that maybe a background worker might be what I need, but I do not know how to work with it. Could someone help walk me through it and provide some code to help me along? Some info, the start form is called 'Start' and the View Records form is called 'Records.' The progress bar is name 'pb'. Thank you in advance to anyone who attempts to help!
Ok, here's the updated code with the error
Imports Office = Microsoft.Office.Core
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Start
Dim Records As New Records
Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
bw.RunWorkerAsync()
End Sub
Private Sub bw_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
' Get the Excel application object.
excel_app = New Excel.Application
' Make Excel visible (optional).
excel_app.Visible = False
' Open the workbook.
workbook = excel_app.Workbooks.Open(xlPath)
sheet_name = "2013"
sheet = excel_app.Worksheets("2013")
Dim ColumnCount, RowCount, TotalCellCount As Long
ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
RowCount = sheet.Range("A1").CurrentRegion.Rows.Count
Records.DataGridView1.ColumnCount = ColumnCount - 1
Records.DataGridView1.RowCount = RowCount - 1
Records.DataGridView1.ColumnHeadersVisible = True
Records.DataGridView1.RowHeadersVisible = True
TotalCellCount = Records.DataGridView1.ColumnCount * Records.DataGridView1.RowCount
pb.Visible = True
pb.Minimum = 0
pb.Value = 0
pb.Maximum = TotalCellCount
Records.DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
Records.DataGridView1.AllowUserToResizeColumns = False
Records.DataGridView1.AllowUserToResizeRows = False
Records.DataGridView1.ReadOnly = True
Records.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
'Loop through each column
Dim cIndex As Integer = 0
While cIndex < ColumnCount
'Loop through and populate each row in column
Dim rIndex As Integer = 0
While rIndex < RowCount - 1
If cIndex = 0 Then
'Set row header titles
Records.DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
If cIndex > 0 Then
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
'Set column header title
Records.DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value
'Change last cell (Result) color Red or Green to represent positive gain or negative loss
If rIndex = RowCount - 2 Then
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
Records.DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
Records.DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
Records.DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
Records.DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
End If
End If
'Update the progress bar after each cell is populated
bw.ReportProgress((rIndex * cIndex) / TotalCellCount)
rIndex = rIndex + 1
End While
'Format all cells in column as currency values
Records.DataGridView1.Columns(cIndex).DefaultCellStyle.Format = "c"
'Make column unsortable
Records.DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable
'Resize all Row Headers so user can see Row Titles without resizing
Records.DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
cIndex = cIndex + 1
End While
Records.DataGridView1.AutoResizeColumns()
End Sub
Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
pb.Value = e.ProgressPercentage
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message, "Background Worker Exception", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
If e.Cancelled Then
'worker was cancelled
Else
'worker completed, open form2 here
pb.Visible = False
Records.ShowDialog()
If (Records.DialogResult) Then
' Close the workbook.
workbook.Close()
' Close the Excel server.
excel_app.Quit()
End If
End If
End If
End Sub
Am I doing this right? And how do I fixed the error?
I would use a background worker on Form1 and then subscribe to its ProgressChanged event to update the progress bar. Then when the worker completes, you can pass that data to Form2 and open it.
Assuming you add a BackgroundWorker called bw to Form1
On the Button click event you need to start the worker by calling bw.RunWorkerAsync
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Setup()
bw.RunWorkerAsync()
End Sub
Private Sub Setup()
' Get the Excel application object.
excel_app = New Excel.Application
' Make Excel visible (optional).
excel_app.Visible = False
' Open the workbook.
workbook = excel_app.Workbooks.Open(xlPath)
sheet_name = "2013"
sheet = excel_app.Worksheets("2013")
Dim ColumnCount, RowCount, TotalCellCount As Long
ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
RowCount = sheet.Range("A1").CurrentRegion.Rows.Count
Records.DataGridView1.ColumnCount = ColumnCount - 1
Records.DataGridView1.RowCount = RowCount - 1
Records.DataGridView1.ColumnHeadersVisible = True
Records.DataGridView1.RowHeadersVisible = True
TotalCellCount = Records.DataGridView1.ColumnCount * Records.DataGridView1.RowCount
pb.Visible = True
pb.Minimum = 0
pb.Value = 0
pb.Maximum = TotalCellCount
Records.DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
Records.DataGridView1.AllowUserToResizeColumns = False
Records.DataGridView1.AllowUserToResizeRows = False
Records.DataGridView1.ReadOnly = True
Records.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
End Sub
Then in the bw.DoWork event you would run the code to fetch the data. Create a form level variable so you can access it in the DoWork and RunWorkerCompleted Events
Dim f as New RecordForm
Private Sub bw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
'Loop through each column
Dim cIndex As Integer = 0
While cIndex < ColumnCount
'Loop through and populate each row in column
Dim rIndex As Integer = 0
While rIndex < RowCount - 1
If cIndex = 0 Then
'Set row header titles
Records.DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
If cIndex > 0 Then
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
End If
'Set column header title
Records.DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value
'Change last cell (Result) color Red or Green to represent positive gain or negative loss
If rIndex = RowCount - 2 Then
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
Records.DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
Records.DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
Records.DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
Records.DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
End If
If Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
Records.DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
End If
End If
'Update the progress bar after each cell is populated
bw.ReportProgress((rIndex * cIndex) / TotalCellCount)
rIndex = rIndex + 1
End While
'Format all cells in column as currency values
Records.DataGridView1.Columns(cIndex).DefaultCellStyle.Format = "c"
'Make column unsortable
Records.DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable
'Resize all Row Headers so user can see Row Titles without resizing
Records.DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
cIndex = cIndex + 1
End While
Records.DataGridView1.AutoResizeColumns()
End Sub
Private Sub bw_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
ProgressBar.Value = e.ProgressPercentage
End Sub
When the worker is finished it will fire its completed event.
Private Sub bw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show(e.Error.Message, "Background Worker Exception", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
If e.Cancelled Then
'worker was cancelled
Else
'worker finished. open Form2
f.Show
End If
End If
End Sub