For context, I have an app that does draft picks for our baseball fantasy league. It records the picks as people make them. I want to add a form with a blank grid that fills in with the picks as they are made and output to my TV. In my main form I have this simple code:
Private Sub SetUpPickBoard()
Dim frmPickBoard As New frmResults
frmPickBoard.Show()
End Sub
Then, in my form load for frmResults, I manually build a datagridview like such:
Private Sub frmResults_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim rsPlayers As DataTable
Dim strSQL = "SELECT ID,DrafterName FROM tblDrafters ORDER BY DraftOrder"
rsPlayers = frmMain.DataAccess.GetDataTable(strSQL)
intDrafterCount = rsPlayers.Rows.Count
For intDrafters = 0 To intDrafterCount - 1
dgvPickBoard.Columns.Add("Drafter" & intDrafters.ToString, rsPlayers.Rows(intDrafters).Item("DrafterName"))
Next
For intCtr = 0 To 22
Dim dgrNewRow As New DataGridViewRow
dgrNewRow.HeaderCell.Value = (intCtr + 1).ToString
dgvPickBoard.Rows.Add(dgrNewRow)
Next
Me.WindowState = FormWindowState.Maximized
MsgBox(dgvPickBoard.Rows.Count & "-" & dgvPickBoard.Columns.Count)
End Sub
The msgbox at the end displays (correctly) 23-10
Then it returns to the main form. Then, in the code for making a pick, I simply tried to change the text of one of the cells in that form with the picked name.
rsResults.datagridview1.rows(rownumber).cells(columnnumber).value=strPickedName
I get index out range error. The rowcount is now 0, as is the columns. Even if I call a function in the frmResults form and pass in the row,column and text values, the datagridview still has zero rows/columns. I don't want to have to rebuild a whole grid from the DB every time I make a pick if possible.
So why is my datagridview 'empty'? It is still displayed in the form. Did I lose the reference to the rows when it left the load function?
I had issues with another form I was trying to manipulate, and I finally stumbled on the issue. The answer is detailed here. Basically, referencing a form by the form name essentially gives you a 'copy' of sorts of your actual form. I changed the reference of the form from frmResults to the object I created when I instanced the form of frmPickBoard (I had to move the definition to a global level, of course). I was then able to access and manipulate all controls in the form I created.