Datagridview control does not populate when the form loads

Hi all.

I'm having an issue populating a datagridview control when my form loads. My code is below. I want to populate the datagridview control when the form loads. The form is opened when the end user clicks the "Edit" button in another form. I even tried moving DataGridView1.DataSource = GetDataTable_Tags() to the "Shown" event and it still does not populate the datagridview control. The only way it loads if I put DataGridView1.DataSource = GetDataTable_Tags() in the Click event of a button. Any ideas what I'm doing wrong?

Thank you in advance.

Code to open the form:
Private Sub EditDetailsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EditDetailsToolStripMenuItem.Click
Dim GridRow As DataGridViewRow = DataGridView1.CurrentRow
        Dim frm As New DocumentEdit
        frm.menuID = GridRow.Cells.Item("MenuID").Value
         frm.Show()

    End Sub

Open in new window


Private Sub DocumentEdit_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.DataSource = GetDataTable_Tags()
     
    End Sub

Private Function GetDataTable_Tags() As DataTable

        Dim con As New SqlConnection
        Dim cmd As New SqlCommand

        con.ConnectionString = "Data Source=myServer;Initial Catalog=myDB;Integrated Security=True"

        con.Open()

        cmd.Connection = con

        cmd.CommandText = "SELECT Tags FROM Menu WHERE MenuID = @MenuID"
        cmd.Parameters.AddWithValue("@MenuID", menuID)

        Dim sda As New SqlDataAdapter(cmd)
        Dim dt As New DataTable()

        DataGridView1.DataSource = Nothing

        sda.Fill(dt)

        DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True     'Word wrap 
        DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells  'Adjust the height of the rows
        DataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter    'Center in the middle cell contents
        DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter   'Center in the middle the column headers
        DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
        DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText

        DataGridView1.AutoGenerateColumns = False

        DataGridView1.ColumnCount = 1   'Set Columns Count

        'Add Columns

        DataGridView1.Columns(0).Name = "Tags"
        DataGridView1.Columns(0).HeaderText = "Tags"
        DataGridView1.Columns(0).DataPropertyName = "Tags"
        DataGridView1.Columns(0).Width = 150

        con.Close()

        Return dt

    End Function

Open in new window

printmediaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Can you verify that your SqlDataAdapter is filling the DataTable with results?

-saige-
0
printmediaAuthor Commented:
Yes because the datagridview control populates when I click a button but not for the form Load and Show events.
0
Ryan ChongBusiness Systems Analyst , ex-Senior Application EngineerCommented:
0
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

aranaCommented:
I dont see where in your code you are filling the datagridview with the DT values

        dataGridView1.DataSource = dt
        dataGridView1.Refresh()
0
printmediaAuthor Commented:
arana, I do in the first line of the Load event:

DataGridView1.DataSource = GetDataTable_Tags()
0
aranaCommented:
oh my bad, you are right, try this

DataGridView1.DataSource = GetDataTable_Tags()
DataGridView1.refresh
0
printmediaAuthor Commented:
Yeah I tried adding the refresh right after I call the GetDataTable_Tags function but still doesn't populate when the form is loaded.
0
aranaCommented:
hmmm have you tried adding that to your SHOW event instead of the LOAD event? I remember I was having a similar if not exactly the same issue and it definately had to do with SHOW vs LOAD ,but dont remember the details, I just remember I had to refresh it before exiting the populating function.
0
printmediaAuthor Commented:
Ryan, I also tried using BindingSource but it still doesn't populate the datagridview control when the form loads.
0
printmediaAuthor Commented:
Yeah I tried that too but it still doesn't populate the datagridview:
 Private Sub DocumentEdit_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        DataGridView1.DataSource = GetDataTable_Tags()
        DataGridView1.Refresh()
        
    End Sub

Open in new window

0
printmediaAuthor Commented:
I think the problem is the fact that I assign menuID in the form that opens the form with the datagridview and maybe it doesn't have the value for menuID when the Load or Shown event executes?
0
it_saigeDeveloperCommented:
Possibly but that is why I asked if you can verify that your SqlDataAdapter fills the DataTable.  You can debug and put a breakpoint here:
sda.Fill(dt)

Open in new window

Check to see if dt has rows.

Just in case, is menuID a property of the Form?  Where is it declared?

-saige-
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
printmediaAuthor Commented:
I declare it at the top

Public menuID As Integer
0
it_saigeDeveloperCommented:
So then your menuID should not be the issue.  Proof of concept -

Form1.vb -
Public Class Form1
	Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
		If TypeOf sender Is Button Then
			Dim btn = CType(sender, Button)
			If btn.Equals(Button1) Then
				Dim frm = New Form2()
				frm.menuID = 5
				frm.Show()
			End If
		End If
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
		Try
			If disposing AndAlso components IsNot Nothing Then
				components.Dispose()
			End If
		Finally
			MyBase.Dispose(disposing)
		End Try
	End Sub

	'Required by the Windows Form Designer
	Private components As System.ComponentModel.IContainer

	'NOTE: The following procedure is required by the Windows Form Designer
	'It can be modified using the Windows Form Designer.  
	'Do not modify it using the code editor.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.Button1 = New System.Windows.Forms.Button()
		Me.SuspendLayout()
		'
		'Button1
		'
		Me.Button1.Location = New System.Drawing.Point(92, 44)
		Me.Button1.Name = "Button1"
		Me.Button1.Size = New System.Drawing.Size(101, 23)
		Me.Button1.TabIndex = 2
		Me.Button1.Text = "Show Form 2"
		Me.Button1.UseVisualStyleBackColor = True
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 111)
		Me.Controls.Add(Me.Button1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)

	End Sub

	Friend WithEvents Button1 As Button
End Class

Open in new window

Form2.vb -
Public Class Form2
	Public menuID As Integer

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles Me.Load
		TextBox1.AppendText($"OnLoad: MenuID is {menuID}{Environment.NewLine}")
	End Sub

	Private Sub OnShown(sender As Object, e As EventArgs) Handles Me.Shown
		TextBox1.AppendText($"OnShown: MenuID is {menuID}{Environment.NewLine}")
	End Sub
End Class

Open in new window

Form2.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form2
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
		Try
			If disposing AndAlso components IsNot Nothing Then
				components.Dispose()
			End If
		Finally
			MyBase.Dispose(disposing)
		End Try
	End Sub

	'Required by the Windows Form Designer
	Private components As System.ComponentModel.IContainer

	'NOTE: The following procedure is required by the Windows Form Designer
	'It can be modified using the Windows Form Designer.  
	'Do not modify it using the code editor.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.SuspendLayout()
		'
		'TextBox1
		'
		Me.TextBox1.Dock = System.Windows.Forms.DockStyle.Fill
		Me.TextBox1.Location = New System.Drawing.Point(0, 0)
		Me.TextBox1.Multiline = True
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.ReadOnly = True
		Me.TextBox1.Size = New System.Drawing.Size(284, 111)
		Me.TextBox1.TabIndex = 0
		'
		'Form2
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 111)
		Me.Controls.Add(Me.TextBox1)
		Me.Name = "Form2"
		Me.Text = "Form2"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub

	Friend WithEvents TextBox1 As TextBox
End Class

Open in new window

Produces the following output -Capture.PNGWhat about if dt has rows?

-saige-
0
printmediaAuthor Commented:
Saige, I added the breakpoint where you suggested and you're right, the dt has no rows.

I'll work on it and let you guys know what I come up with tomorrow.
0
printmediaAuthor Commented:
Saige, it's as you stated, the dt had no rows because it wasn't getting menuID in the Load or Shown events. So instead of populating the datagridview control in those events in the second form, I populate it from the first form right before I show the second form. And now it's working. Thank you for your help!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.