I have a form called "lookuptable" inside that form there is a datagridview "dgv1". I inserted "lookuptable" inside my main form "dashboard" using a panel "panel3".
Here is the code:
Private Sub btnPOS_Click(sender As Object, e As EventArgs) Handles btnPOS.Click
TabControl1.SelectedTab = POS
Dim f As New LookUpTable With {.TopLevel = False, .AutoSize = False}
f.Dock = DockStyle.Fill
Me.Panel3.Controls.Add(f)
f.Show()
End Sub
I am trying to get the value of cell number 5, but I get this error System.NullReferenceException: 'Object reference not set to an instance of an object.'
Here is the code I use to get the value:
Private Sub CustomPrice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PriceTxtBox.Text = LookUpTable.dgv1.CurrentRow.Cells(5).Value
'KeyPreview = True
End Sub
Dgv1 cell 5 has data. So why is it returning null?
CodePudding user response:
As I commented, the current problem you have is because when the code creates the LookUpTable f form in the first code snippet with…
Dim f As New LookUpTable With {.TopLevel = False, .AutoSize = False}
Then f is LOCAL to that method. So, when the code gets to the second code snippet… it is NOT going to know about the form f… in other words, if we tried to access the form f in the second snippet of code with the line…
PriceTxtBox.Text = f.dgv1.CurrentRow.Cells(5).Value.ToString()
The compiler will complain that it does not know what f is…
Therefore, one possible solution (not necessarily the best solution) is to make f a global variable like…
Dim f As LookUpTable
Then change the other snippets of code like below.
Private Sub btnPOS_Click(sender As Object, e As EventArgs) Handles btnPOS.Click
TabControl1.SelectedTab = POS
f = New LookUpTable With {.TopLevel = False, .AutoSize = False}
f.Dock = DockStyle.Fill
Me.Panel3.Controls.Add(f)
f.Show()
End Sub
It is unclear where the code below is called as it appears to be a Load event. However, if it is in the same form as the code above then this should work…
Private Sub CustomPrice_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PriceTxtBox.Text = f.dgv1.CurrentRow.Cells(5).Value
'KeyPreview = True
End Sub
I hope this makes sense.
