Specify which button to run on event vb.net - vb.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim rows, column, j, i
rows = 4
column = 13
For j = 0 To rows - 1
Dim r As New TableRow()
For i = 0 To column - 1
Dim c As New TableCell()
If i = 0 And j = 0 Then
c.Text = "TIME/COURT"
r.Cells.Add(c)
ElseIf i = 0 And j = 1 Then
c.Controls.Add(New LiteralControl("Court A"))
r.Cells.Add(c)
ElseIf i = 0 And j = 2 Then
c.Controls.Add(New LiteralControl("Court B"))
r.Cells.Add(c)
ElseIf i = 0 And j = 3 Then
c.Controls.Add(New LiteralControl("Court C"))
r.Cells.Add(c)
ElseIf i >= 1 And j = 0 Then
c.Controls.Add(New LiteralControl(x & "-" & x + 1))
r.Cells.Add(c)
x += 1
Else
btn = New Button
btn.ID = "btnr" & j & "c" & i
AddHandler btn.Click, AddressOf Change_Colour
c.Controls.Add(btn)
r.Cells.Add(c)
End If
Next
booktable.Rows.Add(r)
Next
End Sub
Protected Sub Change_Colour(sender As Object, e As EventArgs)
btn.BackColor = Drawing.Color.LightGreen
End Sub
When I click on any of the button, only the last button turns light green.
How can I set the button to run the event when I click it?
Can I call the button by button.ID? How?

If multiple buttons can call your Change_Colour routine them you will need to actually determine which one did call it. so you will need something like:
Protected Sub Change_Colour(sender As Object, e As EventArgs)
Dim btn as Button = Ctype(sender, Button)
'here you will need to determine which button is the sender which you could do by checking its name for example
'eg Select case btn.name
'case add stuff here
'end select
btn.BackColor = Drawing.Color.LightGreen
End Sub

Related

ComboBox Control within DatagridView

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

Timer enables, when it should not in vb.net

With a button click i'm trying to check existing rows in the listview.
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles
Button8.Click
If ListViewExtended1.Items.Count >= 0 Then
timer_firstROW.Enabled = True
Else
timer_firstROW.Enabled = False
End If
If ListViewExtended1.Items.Count >= 1 Then
timer_SecondRow.Enabled = True
Else
timer_SecondRow.Enabled = False
End If
If ListViewExtended1.Items.Count >= 2 Then
Timer_ThirdRow.Enabled = True
Else
Timer_ThirdRow.Enabled = False
End If
End Sub
the problem is that i got an invalid argument exception = 1 in timer's sub
Private Sub timer_SecondRow_Tick(sender As Object, e As EventArgs) Handles
timer_SecondRow.Tick
timer_SecondRow.Interval = ListViewExtended1.Items(1).SubItems(3).Text
End Sub
all timers a disabled by default, so when we a checking if else statements and have only 1 item with index 0 in listview, i got that exception, it means that timer enabled, but why..
I tried to make code that, will check existing rows in listview, if row exist, timer will be enabled then timer will send continous messages thourgh serial. if 3 rows existing, 3 rows timers will be enabled and send messages with an interval will assign with "ListViewExtended1.Items(1).SubItems(3).Text". COde of timers:
Private Sub Timer4_Tick(sender As Object, e As EventArgs) Handles
timer_firstROW.Tick
timer_firstROW.Interval = ListViewExtended1.Items(0).SubItems(3).Text
count_for_rx = ListViewExtended1.Items(0).SubItems(4).Text + 1
ListViewExtended1.Items(0).SubItems(4).Text = count_for_rx
GetValueFromlv2Row = "434D4431" & ListViewExtended1.Items(0).SubItems(0).Text & ListViewExtended1.Items(0).SubItems(1).Text & ListViewExtended1.Items(0).SubItems(2).Text.Replace(" ", "")
Dim count As Short
Dim bytestosend(0) As Byte
For count = 1 To GetValueFromlv2Row.Length Step 2 'For count = 249 To Text4.Text * 2 Step 8 page 32
bytestosend(0) = CLng("&H" & Mid(GetValueFromlv2Row, count, 2))
spObj.Write(bytestosend, 0, bytestosend.Length)
Next
spObj.Write(Microsoft.VisualBasic.ControlChars.Cr)
End Sub
Private Sub timer_SecondRow_Tick(sender As Object, e As EventArgs)
Handles timer_SecondRow.Tick
If Not ListViewExtended1.Items(1).ToString() = "" Then
timer_SecondRow.Interval =
ListViewExtended1.Items(1).SubItems(3).Text
count_for_rx = ListViewExtended1.Items(1).SubItems(4).Text + 1
ListViewExtended1.Items(1).SubItems(4).Text = count_for_rx
GetValueFromlv2Row = "434D4431" &
ListViewExtended1.Items(1).SubItems(0).Text &
ListViewExtended1.Items(1).SubItems(1).Text &
ListViewExtended1.Items(1).SubItems(2).Text.Replace(" ", "")
Dim count As Short
Dim bytestosend(0) As Byte
For count = 1 To GetValueFromlv2Row.Length Step 2 'For count = 249
To Text4.Text * 2 Step 8 page 32
bytestosend(0) = CLng("&H" & Mid(GetValueFromlv2Row, count, 2))
spObj.Write(bytestosend, 0, bytestosend.Length)
Next
spObj.Write(Microsoft.VisualBasic.ControlChars.Cr)
Else
timer_SecondRow.Enabled = False
End If
End Sub
Private Sub Timer_ThirdRow_Tick(sender As Object, e As EventArgs) Handles
Timer_ThirdRow.Tick
Timer_ThirdRow.Interval = ListViewExtended1.Items(2).SubItems(3).Text
count_for_rx = ListViewExtended1.Items(2).SubItems(4).Text + 1
ListViewExtended1.Items(2).SubItems(4).Text = count_for_rx
GetValueFromlv2Row = "434D4431" &
ListViewExtended1.Items(2).SubItems(0).Text &
ListViewExtended1.Items(2).SubItems(1).Text &
ListViewExtended1.Items(2).SubItems(2).Text.Replace(" ", "")
Dim count As Short
Dim bytestosend(0) As Byte
For count = 1 To GetValueFromlv2Row.Length Step 2 'For count = 249 To
Text4.Text * 2 Step 8 page 32
bytestosend(0) = CLng("&H" & Mid(GetValueFromlv2Row, count, 2))
spObj.Write(bytestosend, 0, bytestosend.Length)
Next
spObj.Write(Microsoft.VisualBasic.ControlChars.Cr)
End Sub

Computer Click Event Visual Basic

How do I create a random click event driven by the computer? Where the user doesn't get to choose where it clicks?
I have created a table that is 5 buttons wide and 5 buttons tall, and created a click event where the user clicks on a button and the random number value is added onto their score.
Dim RandomNumbers = Enumerable.Range(0, 100).ToList()
Dim RandomNumber As New Random()
For Me.TableColunm = 0 To 4 Step 1
For Me.TableRow = 0 To 4 Step 1
Dim TemporaryNumber = RandomNumbers(RandomNumber.Next(0, RandomNumbers.Count))
RandomNumbers.Remove(CInt(TemporaryNumber))
TableButtons = New Button()
With TableButtons
.Name = "TextBox" & TableColunm.ToString & TableRow.ToString
.Text = TemporaryNumber.ToString
.Width = CInt(Me.Width / 4)
.Left = CInt(TableColunm * (Me.Width / 4))
.Top = TableRow * .Height
'.Tag = TemporaryNumber
AddHandler TableButtons.Click, AddressOf UserTableButtonClickEvent
End With
GameScreen.Controls.Add(TableButtons)
Next TableRow
Next TableColunm
Catch ex As Exception
MsgBox(ex.StackTrace & vbCrLf & "index1= " & TableColunm & vbCrLf & "index2= " & TableRow)
End Try
Private Sub UserTableButtonClickEvent(sender As Object, e As EventArgs)
CType(sender, Button).BackColor = Color.LightSteelBlue
OverAllScoreInteger += CInt(CType(sender, Button).Tag)
GameScreen.UserScoreBox.Text = OverAllScoreInteger.ToString
Dim TableButton As Button = CType(sender, Button)
TableButton.Text = "#"
TableButton.Enabled = False
End Sub
How do I make another event like this but at random?
Enumerate all controls in the GameScreen.Controls collection and add them to a temporary list if they are a button. Then generate a random number in the range of the length of the list and click the button with this index:
Dim TempButtonList As New List(Of Button)
For Each c as Control in GameScreen.Controls
If TypeOf(c) Is Button Then TempButtonList.Add(CType(c, Button))
Next
Dim Rnd as New Random
TempButtonList(rnd.Next(0, TempButtonList.Count-1)).PerformClick()
The PerformClick() method does exactly the same as if you would click that button with your mouse. The If in the loop makes sure you only add buttons in the controls collection, because there may of course be other controls inside.
Complete example
It's probably easier that way (Add a FlowLayoutPanel with Size=275; 275 and two Labels to a Form):
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Rnd As New Random
For i = 1 To 25
Dim b As New Button With {.Text = Rnd.Next(0, 100)}
b.Width = 40
b.Height = 40
FlowLayoutPanel1.Controls.Add(b)
AddHandler b.Click, AddressOf b_hndl
Next
End Sub
Private MyScore As Integer = 0
Private HisScore As Integer = 0
Dim Zug As Boolean = True
Private Sub b_hndl(sender As Object, e As EventArgs)
Dim ThisB As Button = CType(sender, Button)
Dim CurrScore As Integer = CInt(ThisB.Text)
Dim CurrZug As Boolean = Zug
Zug = Not Zug
ThisB.Enabled = False
ThisB.Text = "#"
If CurrZug Then
MyScore += CurrScore
Label1.Text = MyScore.ToString
ComputerMove()
Else
HisScore += CurrScore
Label2.Text = HisScore.ToString
End If
End Sub
Private Sub ComputerMove()
Dim TempButtonList As New List(Of Button)
For Each c As Control In FlowLayoutPanel1.Controls
If TypeOf (c) Is Button Then
Dim thisb As Button = CType(c, Button)
If thisb.Enabled Then TempButtonList.Add(thisb)
End If
Next
If TempButtonList.Count = 0 Then Exit Sub
Dim Rnd As New Random
TempButtonList(Rnd.Next(0, TempButtonList.Count - 1)).PerformClick()
End Sub
End Class
The Dim Zug As Boolean = True determines if the player or the computer is currently in queue to select a button. It is switched on every button press, so the players take turns. The ComputerMove function is executed after the player clicked a button.

VB.Net ComboBox.SelectedIndex always reverts to 1

I am writing a Rock-Paper-Scissors game and have to use a ComboBox to get the user's selection. The problem is that no matter what I select, the selected index always reverts to 1, thus the user always selects rock. How can I fix this?
Imports System.Random
Public Class Form1
Dim played As Integer = 0
Dim won As Integer = 0
Dim lost As Integer = 0
Dim draw As Integer = 0
Dim percent As Single = 0.0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label3.Visible = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As New Random()
Dim b As Integer = a.Next(1, 4)
Dim selection As Integer
ComboBox1.SelectedIndex = selection
If b = 1 Then
Label3.Text = "Rock"
Label3.Visible = True
Select Case selection
Case selection = 1
MsgBox("Draw.")
draw += 1
Case selection = 2
MsgBox("Paper Covers Rock. You win!")
won += 1
Case selection = 3
MsgBox("Rock Crushes Scissors. You lose.")
lost += 1
End Select
ElseIf b = 2 Then
Label3.Text = "Paper"
Label3.Visible = True
Select Case selection
Case selection = 1
MsgBox("Paper Covers Rock. You lose.")
lost += 1
Case selection = 2
MsgBox("Draw.")
draw += 1
Case selection = 3
MsgBox("Scissors Cuts Paper. You win!")
won += 1
End Select
ElseIf b = 3 Then
Label3.Text = "Scissors"
Label3.Visible = True
Select Case selection
Case selection = 1
MsgBox("Rock Crushes Scissors. You win!")
won += 1
Case selection = 2
MsgBox("Scissors Cuts Paper. You lose.")
lost += 1
Case selection = 3
MsgBox("Draw.")
draw += 1
End Select
End If
played += 1
percent = (won / played) * 100
PlayedText.Text = played.ToString
WonText.Text = won.ToString
LostText.Text = lost.ToString
DrawText.Text = draw.ToString
PercentText.Text = percent.ToString
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
I think you need to change this line to
Dim selection As Integer
selection = ComboBox1.SelectedIndex
and the syntax for the SELECT....CASE is
Select Case selection
Case 1
MsgBox("Draw.")
draw += 1
Case 2
MsgBox("Paper Covers Rock. You win!")
won += 1
Case 3
MsgBox("Rock Crushes Scissors. You lose.")
lost += 1
End Select

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